$watch 不会在数组更改时触发 [英] $watch not being triggered on array change
问题描述
我想弄清楚为什么我的 $watch
没有被触发.这是相关控制器的片段:
I'm trying to figure out why my $watch
isn't being triggered. This is a snippet from the relevant 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
显然正在正确更新,因为我的长度限制如下:
On my view, tasks
is clearly being updated correctly as I have its length bound like so:
<span>There are {{tasks.length}} total tasks</span>
我错过了什么?
推荐答案
Try $watch('tasks.length', ...)
或 $watch('tasks', function(...) { ... }, true)
.
默认情况下,$watch 不检查对象是否相等,而只检查参考.所以,$watch('tasks', ...)
将总是简单地返回相同的数组引用,它不会改变.
By default, $watch does not check for object equality, but just for reference. So, $watch('tasks', ...)
will always simply return the same array reference, which isn't changing.
更新: Angular v1.1.4 添加了一个 $watchCollection() 方法来处理这种情况:
Update: Angular v1.1.4 adds a $watchCollection() method to handle this case:
Shallow 监视对象的属性并在任何属性更改时触发(对于数组,这意味着监视数组项,对于对象映射,这意味着监视属性).如果检测到更改,则触发 listener
回调.
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.
这篇关于$watch 不会在数组更改时触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!