AngularJS – $watch $digest $apply Life Cycle

At the heart of angularjs is data binding, in this blog post we will see how angular implements this and what is the life cycle of angular scope. This is very important to understand if you want to optimize your application for performance.

AngularJS Dirty Checking

Dirty checking is a very simply process to check if the value of an expression/variable has changed. Its basically just comparing old value with a new value to see if it has changed. AngularJS uses dirty checking to see if a value of a expression/variable in it’s scope has changed or not, and if it has changed it does the required operation (updating DOM etc).

$watch

$watch is angular method, for dirty checking. Any variable or expression assigned in $scope automatically sets up a $watchExpression in angular. You can create a watch express yourself as well

  
$scope.$watch('variable',function(newValue,oldValue){

});
  

So assigning a variable to $scope or using directives like ng-if, ng-show, ng-repeat etc all create watches in angular scope automatically. e.g $scope.text = ''; creates a $watch for ‘text’ automatically in angular.

$digest

$digest() is angular method, which is invoked internally by angularjs in frequent intervals. In $digest method, angular iterates overall $watches in its scope/child scoples.If any changes are found the resulting DOM operation is done.

$apply

$apply() is a angular method, internally invokes $digest. This method is used when you want to tell angular manually start dirty checking (execute all $watches). Read More here on when to use $apply

$destroy

$destory is both a method and event in angularjs. $destory() method, removes a scope and all its children from dirty checking. $destory event is called by angular when ever a $scope or $controller is destroyed.

  
$scope.$on('$destory',function(){
     
//do clean up here
  
});
  

So we see the $digest and $watch are critical to the working on angularjs.

There a very good explanation on stack overflow about watches and performance which is a worth a read

http://stackoverflow.com/questions/9682092/databinding-in-angularjs/9693933#9693933

excellence-social-linkdin
excellence-social-facebook
excellence-social-instagram
excellence-social-skype