1

I am understanding $digest and $watch functions. I found that whenever value of model changes then angular runs $digest again and if value of model changes very frequently then angular throws infinite loop error.

Example from angular

Ok then, this example throws infinite error

<div ng-repeat="user in getUsers()">{{ user.name }}</div>

...

 $scope.getUsers = function() {
    return [ { name: 'Hank' }, { name: 'Francisco' } ];
  };

BUT this code does not throw any infinite loop error. Why is it so ? This example should also throw an error

 <div> {{getUsers()}}</div>

...

 $scope.getUsers = function() {
    return [ { name: 'Hank' }, { name: 'Francisco' } ];
  };

because as per documentation getUser function anyways returning a new array everytime in both cases.

Thanks

voila
  • 1,594
  • 2
  • 19
  • 38
  • @JenishRabadiya : My question is why second snippet is not throwing any error while the first code does. – voila Mar 28 '16 at 07:07

1 Answers1

3

Because you are using the ng-repeat directive. It has the potential to run thousands or hundreds of thousands of iterations, so an error is thrown even if you have only 2 items in the array.

Sort of a precaution.

Should be this:

<div ng-repeat="user in getUsers()">{{ user.name }}</div>

...

var users = [ { name: 'Hank' }, { name: 'Francisco' } ];

$scope.getUsers = function() {
    // Same array returned each iteration, no model changes.
    return users;
};
George Kagan
  • 5,913
  • 8
  • 46
  • 50
  • See this - http://stackoverflow.com/a/33847397/178163 Basically, since you return a new array each iteration, angular thinks the model changed. – George Kagan Mar 28 '16 at 07:17