Chapter 11
Or, we could change the default strategy and propagate model updates only after the
user leaves the input field:
//DOM -> Model updates
element.bind('blur', function () {
scope.$apply(function () {
modelSetter(scope, element.val());
});
});
Whatever the strategy chosen, the important point here is that model-changes tracking
process need to be started explicitly. This might come as a surprise since by simply
using built-in AngularJS directives we can see "magic" happening without calling the
$apply method all over the place. But those calls are present in the built-in directives'
code. It is just that standard directives and services ($http, $timeout, $location, and
so on) take care of starting the whole model-changes tracking process for us.
AngularJS starts the model-changes tracking machinery by calling the
$apply method on a scope. This call is done inside standard services
and directives in response to network activity, DOM events, JavaScript
timers or browser location changes.
Enter the $digest loop
In AngularJS terminology the process of detecting model changes is called $digest
loop (or $digest cycle).The name comes from the $digest method available on
Scope instances. This method is invoked as part of the $apply call and it will
evaluate all the watches registered on all the scopes.
But why does the $digest loop exist in AngularJS? And how it does its job of
determining what has changed in the model? AngularJS the $digest loop exists to
address two related problems:
- Decide which parts of the model have changed and which DOM properties
should be updated as a result. The goal here is to make this process as easy
as possible for developers. We should just mutate model properties and
have AngularJS directives automatically figure out parts of the document
to be repainted. - Eliminate unnecessary repaints to increase performance and avoid UI
flickering. AngularJS achieves this by postponing DOM repaints till the very
last possible moment when the model stabilizes (all the model values were
calculated and ready to drive UI rendering).