Sabarish Sankar Sabarish Sankar - 1 year ago 327
AngularJS Question

Error: 10 $digest() iterations reached. Aborting! with dynamic sortby predicate

I have the following code which repeats and displays name of the user and his score:

<div ng-controller="AngularCtrl" ng-app>
<div ng-repeat="user in users | orderBy:predicate:reverse | limitTo:10">
<div ng-init="">
{{}} and {{user.score}}

And the corresponding angular controller.

function AngularCtrl($scope) {
$scope.predicate = 'score';
$scope.reverse = true;
$scope.users = [{id: 1, name: 'John'}, {id: 2, name: 'Ken'}, {id: 3, name: 'smith'}, {id: 4, name: 'kevin'}, {id: 5, name: 'bob'}, {id: 6, name: 'Dev'}, {id: 7, name: 'Joe'}, {id: 8, name: 'kevin'}, {id: 9, name: 'John'}, {id: 10, name: 'Ken'}, {id: 11, name: 'John'}, {id: 1, name: 'John'}, {id: 2, name: 'Ken'}, {id: 3, name: 'smith'}, {id: 4, name: 'kevin'}, {id: 5, name: 'bob'}, {id: 6, name: 'Dev'}, {id: 7, name: 'Joe'}, {id: 8, name: 'kevin'}, {id: 9, name: 'John'}, {id: 10, name: 'Ken'}]

When I run the above code, I get the Error: 10 $digest() iterations reached. Aborting! error in my console.

I have created jsfiddle for same.

The sort predicate is being initalized only inside the ng-repeat and also the limit is being applied on the number of objects. so I feel having both the sortby and limitTo watchers together is the reason for error.

If the $scope.reverse is false (ascending order of score), then it does not error.

Can anyone help me understand what is wrong here? Much appreciate your help.

Answer Source

Please check this jsFiddle: (The code is basically the same you posted but I use an element instead of the window to bind the scroll events).

As far as I can see, there is no problem with the code you posted. The error you mentioned normally occurs when you create a loop of changes over a property. For example, like when you watch for changes on a certain property and then change the value of that property on the listener:

$scope.$watch('users', function(value) {
  $scope.users = [];

This will result on an error message:

Uncaught Error: 10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations: ...

Make sure that your code doesn't have this kind of situations.


This is your problem:

<div ng-init=""> 

You shouldn't change objects/models during the render or otherwise it will force a new render (and consequently a loop, which causes the 'Error: 10 $digest() iterations reached. Aborting!').

If you want to update the model, do it on the Controller or on a Directive, never on the view. angularjs documentation recommends not to use the ng-init exactly to avoid these kind of situations:

Use ngInit directive in templates (for toy/example apps only, not recommended for real applications)

Here's a jsFiddle with an working example:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download