Angular.js方法的调用比我认为的要多

时间:2015-12-18 21:57:52

标签: javascript angularjs

我的问题是,为什么当我点击一个复选框时它会调用todoList.remaining()3次?如果我是诚实的,我甚至不理解触发todoList.remaining()的事件处理程序是什么?我的代码如下,但这里是我的示例链接: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;
  };

});

2 个答案:

答案 0 :(得分:3)

这是因为模板中的{{todoList.remaining()}}。每当“观察”变量发生变化时,角度会重新评估所有表达式,以确保它是最新的。

这是与您有关的问题:Is expression inside ng-show fired after every model change in AngularJS?

答案 1 :(得分:2)

这是angularJS用于使您的视图保持最新的脏跟踪。在你的例子中,它是剩余的todos,它将继续评估值,直到它稳定。当你单击复选框时,angular将评估函数,因为$ scope.todo.done已经改变,并且它会一直这样做,直到函数值稳定为止。 详细了解dirty tracking