加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angularjs – $watch不会触发数组更改

发布时间:2020-12-17 08:59:11 所属栏目:安全 来源:网络整理
导读:我想知道为什么我的$手表没有被触发。这是相关控制器的代码段: $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.$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
};

在我看来,任务显然正在正确更新,因为我的长度限制像这样:

<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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读