javascript - Angular.js 方法被调用的次数超出了我的预期

标签 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;
  };

});

最佳答案

发生这种情况是因为模板内的 {{todoList.remaining()}} 。每当某些“监视”变量发生变化时,Angular 就会重新评估所有表达式以确保其是最新的。

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

关于javascript - Angular.js 方法被调用的次数超出了我的预期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34364569/

相关文章:

javascript - 生成: true not working in loopback 4

javascript - Google map 对地点进行地理编码

javascript - Angular : ng-repeat depending on state of other object

javascript - Angular UI 按钮指令,事件 radio 未正确更新

javascript - 在哪里放置资源特定逻辑

javascript - 单击表格标题对数组进行排序

javascript - 从 Firefox 获取 HWND

javascript - 从浏览器隐藏服务器端技术信息

javascript - angularjs XXXService.XXXfunction 不是一个函数

javascript - 参数为 "Cannot match any routes"的 Angular 嵌套路由