0

I have a service that holds tasks for my todo app. It has getActive() and getCompleted() methods that return an array with the active, and completed method respectively.

I want to show the number of compelted, active and total tasks. I was doing this with angular's $watch

$scope.active = tasks.getActive().length;
$scope.completed = tasks.getCompleted().length;

$scope.$watch(tasks.getActive, function() {
  $scope.active = tasks.getActive().length;
}); 

$scope.$watch(tasks.getCompleted, function() {
  $scope.completed = tasks.getCompleted().length;
});

It works fine, but it throws lot of errors to the console everytime I change a task state or I delete it.

Uncaught Error: 10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations:
2
  • The best approach to this for me has been to define something like getActiveLength() and getCompletedLength() and watch those functions instead. I believe that calling the function within a watch that's watching it will recursively trigger another watch.
    – Manny D
    Jun 21, 2013 at 15:36
  • You may want to check out the source code of the demo app @ todomvc.com/architecture-examples/angularjs-perf/#
    – Mike Pugh
    Jun 21, 2013 at 15:38

2 Answers 2

1

I think you don't need those watches. In AngularJS, most expressions in the view get updated on the fly, so you can use tasks.getCompleted().length directly, like:

$scope.active = function(){
    return tasks.getActive().length;
};
$scope.completed = function(){
    return tasks.getCompleted().length;
};

As for the 10 digests error, see Maxing out on $digest iterations.

0

I don't think you should call getActive and getCompleted again in your $watch callback, you can actually specify it as a function(newValue, oldValue) and have the new and old values without having to call the method again, which may result in a $digest loop.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.