A
A
Artem Shchurin2016-02-28 18:51:58
Angular
Artem Shchurin, 2016-02-28 18:51:58

Why doesn't $digest work when data is changed in the controller?

Good day!
More than once I have encountered the fact that we change data in the controller or in the directive, and in order to apply changes on the page, we have to call $scope.$$phase || $scope.$digest();or apply changes inside $scope.$apply(function(){//my code}), at what moments does $digest work?
Code example:

(function() {
    'use strict';

    var HomeController = function($scope, productService) {
      var _this = this;
      _this.products = [];

      productService.getProducts()
        .then(function(data) {
          _this.products = data;
        });

      setTimeout(function() {
        _this.products = _this.products.splice(1, 2);
        $scope.$$phase || $scope.$digest();
      }, 3000);
    };

    HomeController.$inject = ['$scope', 'ProductService'];
    angular.module('auction').controller('HomeController', HomeController);
  }());

<ul class="list-unstyled" id="items-list">
      <li class="col-md-4" ng-repeat="product in ctrl.products">
          <div class="row">
              <div class="product-description-holder col-xs-8">
                  <h2><a ng-href="#/product/{{ product.id }}">{{ product.title }}</a></h2>
                  <p>{{ product.description }}</p>
              </div>
          </div>
      </li>
  </ul>

When initializing the controller, everything is fine, ng-repeat tilts the products, but after changing the _products variable by timer, I expect to see 2 products, what happens if you run $digest manually
PS SetTimeout is used as an example, they say the data is changed from outside

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dasha Tsiklauri, 2016-02-28
@dasha_programmist

replace setTimeout with $timeout, respectively, you need to inject $timeout
manual into the controller method

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question