Mastering Web Application

(Rick Simeone) #1

Writing Robust AngularJS Web Applications


If you run this example and inspect output of the console, you will notice that two
log entries are written for each change in the field.


Any given $digest loop will have at least one turn, usually two. It
means that each individual watch expression will be evaluated twice
per $digest loop (before the browser leaves JavaScript execution
context and moves to UI rendering).

Unstable models


There are cases where two turns inside the $digest loop are not enough to stabilize
the model. Worse yet, it is possible to get into a situation where model never
stabilizes! Let's consider a very simple example of the markup:


<span>Random value: {{random()}}</span>

Where the random() function is defined on a scope like:


$scope.random = Math.random;

Here a watch expression is equal to Math.random() and it will (most probably)
evaluate to a different value on each turn of the $digest loop. This means that each
turn will be marked as "dirty" and a new turn will be needed. The situation will
keep repeating itself over and over again, until AngularJS decides that the model is
unstable, and will break the $digest loop.


By default AngularJS will try to execute up to 10 turns before giving
up, declaring the model as unstable and breaking the $digest loop.

Upon breaking the $digest loop AngularJS will report an error (using the
$exceptionHandler service which, by default, logs errors on a console). The
reported error will contain information about the last five unstable watches (with
their new and old values). In majority of cases there will be only one unstable watch,
making it easy to find a culprit.


After the $digest loop gets aborted, the JavaScript thread leaves "AngularJS world",
and there will be nothing stopping a browser from moving to the rendering context.
In this case, users will get their page rendered with the value computed by watchers
in the last turn of the $digest loop.

Free download pdf