$腕表不被触发阵列更改 [英] $watch not being triggered on array change

查看:126
本文介绍了$腕表不被触发阵列更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出为什么我的 $腕表不被触发。这是从相关负责一个片段:

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

在我看来,任务显然是正确更新,因为我已经其长度的约束,像这样:

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>

我是什么失踪?

推荐答案

尝试 $腕表('tasks.length',...) $腕表('任务',函数(...){...},真实)

在默认情况下, $看不检查对象的平等,而是只为参考。因此, $腕表('任务',...)总是简单地返回相同的数组引用,这是不会改变。

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.

更新:角V1.1.4增加了一个<一个href=\"http://$c$c.angularjs.org/1.1.4/docs/api/ng.%24rootScope.Scope#%24watchCollection\">$watchCollection()方法来处理这​​种情况:

Update: Angular v1.1.4 adds a $watchCollection() method to handle this case:

浅手表的对象,每当任何属性的改变火的属性(数组这意味着观望数组项,对象映射这意味着看属性)。如果检测到听者的变化回调被激发。

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.

这篇关于$腕表不被触发阵列更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆