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

问题描述

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

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:

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

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

09-12 12:55