我想在订单上附加 watch
。我不知道如何将监视添加到字典列表内的变量。
内部 Controller ,
cart_list = [{'order':'single'},{'order':'single'},{'order':'twice'}];
for (var i = 0; i < $scope.cart_list.length; i++) {
$scope.$watch('cart_list[i].order', function() {
console.log("Inside watch");
if($scope.cart_list[i].order=='single'){
console.log("with single order");
}
}
}
这给了我错误,
TypeError: Cannot read property 'order' of undefined
最佳答案
我能想到的让这个 watch 工作的唯一方法是在 watch 中使用函数表达式。代码变成这样
for (var i = 0; i < $scope.cart_list.length; i++) {
setupWatch($scope.cart_list[i]);
}
function setupWatch(item) {
$scope.$watch(function () {
return item
}, function (newValue, oldValue) {
console.log("Inside watch");
if (newValue.order == 'single') {
console.log("with single order");
}
}, true);
}
我还没有尝试过,但我认为这应该可行。
此外,我还添加了严格的对象相等性作为最后一个参数。
关于javascript - 将 $watch 附加到 dict 列表内的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29916719/