0

My question is, why when I click a checkbox does it call todoList.remaining() 3 times? If I'm being honest, I don't even understand what the event handlers are that trigger todoList.remaining()? My code is below, but here's a link to my example: http://www.search-this.com/examples/angular/

        <div ng-controller="TodoListController as todoList">
        <span>{{todoList.remaining()}} of {{todoList.todos.length}} remaining</span>

        <ul class="unstyled">
            <li ng-repeat="todo in todoList.todos">
                <input type="checkbox" ng-model="todo.done">
                <span class="done-{{todo.done}}">{{todo.text}}</span>
            </li>
        </ul></div>

javascript

angular.module('todoApp', [])
 .controller('TodoListController', function () {

  var todoList = this;

  todoList.todos = [
    { text: 'learn angular', done: true, type: 'work', id: 1 },
    { text: 'build an angular app', done: false, type: 'work', id: 2 },
    { text: 'learn SASS', done: false, type: 'work', id: 3 },
    { text: 'update iOS', done: true, type: 'home', id: 4 },
    { text: 'play FIFA', done: false, type: 'home', id: 5 },
  ];

  todoList.remaining = function () {
      console.log('foo');
      var count = 0;
      angular.forEach(todoList.todos, function (todo) {
          count += todo.done ? 0 : 1;
      });
      return count;
  };

});
Mark
  • 2,543
  • 6
  • 33
  • 44

2 Answers2

3

It happens because of {{todoList.remaining()}} inside the template. Whenever some 'watched' variable changes, angular reevaluates all the expressions to make sure it is up to date.

This is a related question to yours: Is expression inside ng-show fired after every model change in AngularJS?

Community
  • 1
  • 1
jonasnas
  • 3,540
  • 1
  • 23
  • 32
2

This the dirty tracking that angularJS use for keeping your view up to date. In your example it's the remaining-todos, it will keep evaluating the value until it stabilizes. when you click on the checkbox, angular will evaluate the function because $scope.todo.done has changed, and it will keep doing that until function value stabilizes. Read more on dirty tracking.

Community
  • 1
  • 1
Nizar
  • 481
  • 5
  • 8