Knowledge Management Banner

Knowledge Management Banner

AngularJS : How does AngularJS works ? or What is AngularJS ? or What is $apply and $digest cycle : Part 1

What is AngularJS ?
  • AngularJs is a javascript framework which is used for building web applications.
How does angularJs Works ?

In order to understand working of angularJs, it is important to understand $apply and $digest

AngularJs offers advanced functionality of two way data binding

  • When you change something in view the model automatically gets updated 
  • When you change something in model the view is automatically updated

Let us understand the following concepts

$watch & $watchlist
  • For a scope object and every model binding on ui watchers are added to it.
  • Along with watcher the argument passed to it are the listeners, so when the value of model changes the listeners are called to update the HTML, thus these watchers added to every model and its properties are added in watchlist.

$digest Cycle
  • In digest cycle of angularJs all the watchers in the watch list are triggered and it evaluates the model whether the value has changed or not.
  • If values are changed than corresponding listener is called to make change in html ( This is also called dirty checking, which is done in digest cycle ).

AngularJs Work Flow
  • When there is change in ng-model or directive ng-click the angularJs will internally call $scope.$apply() which will further automatically call $rootscope.$digest(), digest cycle will fire all watcher and accordingly update the view if there is change in model.
  • $digest cycle will run minimum 2 times, first time to update view, 2nd time to ensure that the changes are reflected in view.

When to call $apply() manually ?
  • When ever the model is changed within angular context $apply cycle is called automatically  which in return calls $digest.
  • AngularJs built in directive do this automatically so that the view is updated.
  • If there is change in angular model outside the angular context than it is necessary to let angularJs know that the change has occured in model, hence it is necessary to call $apply() manually, in order to reflect change in view.

How many times does $digest loop runs ?
  • Digest cycle will run minimum 2 times, First time, in order to make changes in view and second time to ensure that the changes are reflected in view. 
  • But there can be condition when the listener of watcher in digest cycle may cause change in model which will again trigger digest cycle and this will go on till there are no changes and the model is stable.
  • In order to avoid the digest cycle running in infinite loop, there is maximum count of 10 in angularJs. Thus the digest cycle can loop at max 10 times



No comments

Powered by Blogger.