What causes a digest loop for two-way data bindings?

How does AngularJS implement two-way data binding? The idea of ​​updating the model is understandable, i.e. It can be achieved through JS listeners, but I wanted to understand the model for viewing updates? Since angular models are js variables in the core, how does angular listen on js vars?

I know that each model has a clock that compares the new value with the old, but what causes this check (js implementation)?

Does it use Javascripts observers or a time interval for validation?

+2
source share
1 answer

Angular defines the concept of a so-called digest cycle. This loop can be thought of as a loop during which Angular checks to see if any changes to all variables observed by all areas of $. So if you have the $ scope.myVar defined in your controller, and this variable has been marked for viewing, then you explicitly tell Angular to track the changes on myVar in each iteration of the loop.

Basically, AngularJS associates event handlers with any element that interacts with Angular ( $scope , directive , ...), every time the event fires, $apply is called, which internally calls $digest , which will re-evaluate all $watches .

AngularJS made a reasonable assumption that model changes only occur during user interactions / events:

  • DOM Events
  • XHR responses calling callbacks
  • Change browser location
  • Timers (setTimout, setInterval) calling callbacks

Or trigger on specific events

  • Input Directives + ngModel, ngClick, ngMouseOver, etc.
  • $ http and $ resource
  • $ location
  • $ timeout

enter image description here

When one of these “assumptions” is triggered, the digest cycle begins:

To quote Pawel Kozlowski, Mastering Web Application Development Using AngularJS :

AngularJS does not use any polling mechanism to periodically check model changes

More details

Check out https://www.youtube.com/watch?v=SYuc1oSjhhY for a deep dive into the digest cycle.

+3
source

Source: https://habr.com/ru/post/1260306/


All Articles