我试图找出为什么我的 $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/