krzyhub krzyhub - 3 months ago 11
AngularJS Question

Infinite $digest Loop with sortby

I have very simple form:

<form>
<label><input type="radio" name="sortby" value="created" checked ng-model="sortby"> By creation date</label>
<label><input type="radio" name="sortby" value="text" ng-model="sortby"> By text</label>
</form>

<div ng-repeat="todo in TodoList.getTodos() | orderBy: sortby">
<h1>{{ todo.text }}</h1>
</div>


But this produces
Error: $rootScope:infdig. Infinite $digest Loop
when switch sorting. How to make this switch working?

Answer

it seems like your TodoList.getTodos() function generates a new array every time it is called, this common mistake is explained at https://docs.angularjs.org/error/$rootScope/infdig. The solution is to keep your todoList in a variable, which should be updated only when the list is changed, and TodoList.getTodos() function just returns this variable:

// should be updated only when the list is changed 
var todoList= [ YOUR TODO LIST ];

TodoList.getTodos = function() {
  return todoList;
};