gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 19:34:36 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com