Skip to content Skip to sidebar Skip to footer

How To Prevent "error: $rootscope:infdig" When Different Value Each Time Is Intended Behavior

I'm working on a page using AngularJS(with Aria, Animate, Material, Messages, Sanitize and Route), everyting is working fine but I have a bit of a problem. Angular likes to throw '

Solution 1:

This won't work, because of how Interpolation Bindings {{ }} are evaluated.

Interpolation Bindings are not evaluated once per page reload. They are evaluated every $digest cycle, to determine if their value needs to be updated, which is the cornerstone of how angular two way binding works. Unfortunately, functions which are executed inside an Interpolation Binding cause another $digest cycle to fire, in order to determine if the function call has made any changes requiring other Bindings to be updated.

In this case, that creates a bit of an issue, since the $digest will never be stable. every call to the $digest generates a new randomJoke, which causes the $digest to fire again. If you review the infdig error, you can actually see the Watchers fired in the last 5 iterations showing 5 different jokes in the oldVal and newVal.

The infdig error is actually a failsafe, angular stops the digest after 10 iterations, to ensure that you don't lock the browser up completely. In practice, you could use the code this way, but the application would suffer from some very poor performance as a result.

The better method is to bind to a variable that is assigned to the result of your function call, which is evaluated once, during controller initialization.

Solution 2:

Looks like binding to function is the culprit which causes the infinite digest cycle: Explanantion

To fix this, bind to a variable instead: <article><br>{{randomJoke}}</article>

And in the controller, instead of randomJoke() function, assign a randomly generated joke to a variable:

$scope.randomJoke = $scope.jokes[Math.floor(Math.random() * $scope.jokes.length)];

Plunker: https://plnkr.co/edit/UPc3CGhPgyfAWafI92b4?p=preview

Post a Comment for "How To Prevent "error: $rootscope:infdig" When Different Value Each Time Is Intended Behavior"