0

I'm unable to understand how $digest works. According to the answer given in Angular $scope.$digest vs $scope.$apply

" $digest() will update the current scope and any child scopes. $apply() will update every scope. So most of the time $digest() will be what you want and more efficient "

But in my plnkr when I do

$rootScope.company = "Google";  

calling $digest() on the second controller,the change gets updated in parent scope also. Did I make any mistake ?

Plnkr : http://plnkr.co/edit/LTBWTWf7hxlfc5niXsGN?p=preview

Community
  • 1
  • 1
user1184100
  • 6,742
  • 29
  • 80
  • 121

2 Answers2

0

I've given a look at your code and I found it pretty interesting! First of all I would suggest you to play with the timeout values, for example: I've changed the timeout value of the second controller to 1000 ms and found out that now the two companies with 'Google' where the second and the third ones.

But apart from this I've noticed that in the third controller you wrap the initialisation inside an $apply, turning the code of the third controller to this

app.controller('ThirdCtrl', function($scope, $rootScope) {
 $scope.name = 'Third';

  setTimeout(function() {
      $scope.name = "I'm Third";
     $rootScope.company = "Amazon";
     $scope.$digest();
  },500);
});

definitely solved the "error" for me due to the fact the $apply being called in the third controller was also updating $rootScope, doing its job properly! :D

Anyway, for this solution I wouldn't suggest you using $scope rather than $rootScope, you might experience unwanted updates and your final application might be unstable.

Lucat
  • 2,242
  • 1
  • 30
  • 41
0
  • $apply :

is the function which is responsible to execute the entire list of watchers of all available scope in the application by invoking $digest on rootScope ($rootScope.$digest()).

This means that every time we call $apply() we execute a new life complete cycle of the application.

  • $digest :

AngularJS executes in cycles, which is termed as $digest and this $digest is responsible for evaluating changes between models and views and update UI and Model to be in sync.

As already described above that $apply invokes $digest on rootScope and its means that it reevaluate all watchers in all available scope and this may cause a performance hit for large scope hierarchy.

aitnasser
  • 1,216
  • 1
  • 9
  • 23