angularjs - 数组更改时未触发 $watch

标签 angularjs angularjs-scope

我试图找出为什么我的 $watch 没有被触发。这是相关 Controller 的片段:

$scope.$watch('tasks', function (newValue, oldValue) {
    //do some stuff
    //only enters here once
    //newValue and oldValue are equal at that point
});

$scope.tasks = tasksService.tasks();

$scope.addTask = function (taskCreationString) {
    tasksService.addTask(taskCreationString);//modifies tasks array
};

在我看来,tasks 显然已正确更新,因为我对其长度进行了限制,如下所示:

<span>There are {{tasks.length}} total tasks</span>

我错过了什么?

最佳答案

尝试 $watch('tasks.length', ...)$watch('tasks', function(...) { ... }, true).

默认情况下,$watch不检查对象相等性,仅供引用。因此,$watch('tasks', ...) 将始终简单地返回相同的数组引用,该引用不会改变。

更新: Angular v1.1.4 添加了 $watchCollection()处理这种情况的方法:

Shallow watches the properties of an object and fires whenever any of the properties change (for arrays this implies watching the array items, for object maps this implies watching the properties). If a change is detected the listener callback is fired.

关于angularjs - 数组更改时未触发 $watch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15363259/

相关文章:

javascript - Angular : Showing only checked items in a checkbox list

javascript - 更新 Controller 变量更改指令创建的元素

javascript - Angular 过滤器未按预期工作

javascript - Angular $scope 对象未在 View 中更新

javascript - 如何通过从angular的ng-init传递的Id获取html元素

javascript - 如果 GET 请求返回 404 错误,则中断 javascript 链

javascript - Angular ng-init $scope 函数未正确更新模型?

angularjs - 在 Jasmine 测试中获取自定义指令的 Controller 范围

angularjs - 在 AngularJS 中不使用时如何从范围中删除?

javascript - ng-repeat ="(key, value)"不能将 {{key}} 的值用作另一个指令的全局范围的一部分