gpt4 book ai didi

javascript - $watchCollection 不适用于数组

转载 作者:搜寻专家 更新时间:2023-11-01 05:12:11 26 4
gpt4 key购买 nike

我正在使用 $watchCollection 来观察数组长度的变化。但是当我将任何项目添加到数组时它似乎不起作用。我哪里出错了?

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {

$scope.count;
$scope.Items = {
"Cars" : [
{
"id" : 1,
"name" : "Mercedes"
},
{
"id": 2,
"name" : "Ferrari"
}

],
"Bikes" : [
{
"id" : 1,
"name" : "Ducati"
},
{
"id": 2,
"name" : "Yamaha"
}

]
}

$scope.addCar = function() {
$scope.Items.Cars.push({
'id' : 3,
"name" : "random name"
})
}

$scope.$watchCollection($scope.Items.Cars, function(newNames, oldNames) {
$scope.count = $scope.Items.Cars.length;
console.log($scope.count);
})

});

演示:http://plnkr.co/edit/dSloJazZgr3mMevIHOe8?p=preview

最佳答案

您应该将表达式作为第一个变量传递给 $watchCollection ,不是对象:

$scope.$watchCollection('Items.Cars', function(newNames, oldNames) {
$scope.count = $scope.Items.Cars.length;
console.log($scope.count);
})

plnkr example .

关于javascript - $watchCollection 不适用于数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20999076/

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