【问题标题】:$scope.$watch on an array is not updating when the values are added from a directive从指令添加值时,数组上的 $scope.$watch 未更新
【发布时间】:2014-07-04 08:10:20
【问题描述】:

我确定这只是一个新手的错误...这是 plunker:http://plnkr.co/edit/L5702XAtQwBRmzP2kqoA?p=preview

我有一个指令可以根据选中的复选框更新值:

// --- 8< ---
// Detect click on checkbox, get value, etc... then:
// --- 8< ---
scope.$apply(function() {
    if ($this.prop("checked")) {
        selected.push(value);
    } else {
        for (var i = 0; i < selected.length; i++) {
            if (selected[i] == value) {
                selected.splice(i, 1);
                break;
            }
        }
    }

    console.log("selected updated to: " + selected)
});

我正在页面控制器中查看该集合:

$scope.$watch("model.selected", function(selected) {
    console.log("----- Controller updated with: ", selected);
});

此处的console.log 语句仅在页面首次加载时显示一次。但是,在页面上,我有一个显示所选值数组的绑定:

Selected: {{ model.selected }}

确实更新了。

为什么我的手表也没有更新?

【问题讨论】:

    标签: javascript angularjs angularjs-directive


    【解决方案1】:

    要在集合(即数组)添加、删除、更改值时收到通知,您需要使用 $scope.$watchCollection 方法。

    改变这个:

    $scope.$watch("model.selected", function(selected) {
        console.log("----- Controller updated with: ", selected);
    });
    

    到这里:

    $scope.$watchCollection("model.selected", function(selected) {
        console.log("----- Controller updated with: ", selected);
    });
    

    这是更新的 plunkr:

    http://plnkr.co/edit/f2xCge2ragh5uWKRRwof?p=preview

    【讨论】:

    • 嗯,我在一件事上是对的——这是一个菜鸟的错误。我以前什至没有听说过watchCollection。谢谢!
    【解决方案2】:

    如果你只需要监控长度变化,那么使用

    $scope.$watch("model.selected.length", function() {
        console.log("----- Controller updated with: ", $scope.model.selected);
    });
    

    注意:只看长度会快很多。

    【讨论】:

    • 很好的建议,我不得不承认我没想到!不过在这种情况下,我确实需要观察数组中的哪些变化(这只是一个简化的示例)-但感谢您指出。
    猜你喜欢
    • 2012-06-23
    • 1970-01-01
    • 2015-05-03
    • 1970-01-01
    • 2015-12-11
    • 1970-01-01
    • 2015-12-11
    • 2015-11-09
    • 2016-08-05
    相关资源
    最近更新 更多