Mastering Web Application

(Rick Simeone) #1
Chapter 4

Given an array of different items stored in the items variable on a scope, the random
filter could be used in a template like:


{{items | random}}

The preceding code, upon execution, will print out a random value so it might seem
that it behaves correctly. It is only upon expecting browser's console we can realize
that in fact an error is logged:


Uncaught Error: 10 $digest() iterations reached. Aborting!


This error means that an expression is yielding different results each time it is
being evaluated. AngularJS sees a constantly changing model and re-evaluates an
expression, hoping that it will stabilize. After repeating this process ten times the
digest is aborted, the last result printed and the error logged in a console. Chapter 11,
Writing Robust AngularJS Web Applications goes into deeper discussion of these topics,
and explains inner workings of AngularJS that should make reasons for this error
easier to understand.


In situations like those the solution is to calculate a random value in a controller,
before a template is rendered:


.controller('RandomCtrl', function ($scope) {

$scope.items = new Array(1000);
for (var i=0; i<$scope.items.length; i++) {
$scope.items[i] = i;
}

$scope.randomValue = Math.floor(Math.random() * $scope.items.length);
});

Like this a random value will be calculated before template processing and we can
safely use the {{randomValue}} expression to output the prepared value.


If your function can generate different results for the same input it is not a good
candidate for a filter. Invoke this function from a controller instead and leave
AngularJS to render pre-calculated value.

Free download pdf