我在主应用程序 Controller 中定义了一个 items 对象,它有 3 个 bool 项。我正在将此对象发送到具有隔离范围的指令。在此指令中,我使用 ng-repeat 迭代接收到的对象,并使用 items 对象中的 ng-model = item 创建复选框。
但是我无法观察 items 对象的更改(由 ng-model 在指令上完成)。我放置的 $watchCollection 似乎不起作用。
JavaScript:
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', function($scope) {
$scope.items = {
item1: true,
item2: false,
item3: true
};
$scope.$watchCollection('items', function(newVal, oldVal) {
console.log(oldVal, newVal);
});
});
myApp.directive('testDirective', function() {
return {
restrict: 'E',
replace: true,
scope: {
items: '='
},
template: "<div ng-repeat='(item,val) in items'><label><input type='checkbox' ng-model='val'/>{{item}}</label></div>"
}
});
HTML:
<div ng-controller="MyCtrl">
<test-directive items="items"></test-directive>
</div>
但是,如果在指令 HTML 中,我不使用 ng-repeat 并手动创建单独的复选框,则 $watchCollection 会正确监视更改:
<div>
<label>
<input type='checkbox' ng-model='items.item1' />Item1</label>
<label>
<input type='checkbox' ng-model='items.item2' />Item2</label>
<label>
<input type='checkbox' ng-model='items.item3' />Item3</label>
</div>
下面是问题的JSFiddle链接: https://jsfiddle.net/rishabh1990/0kb6tezd/
最佳答案
$watchCollection仅在您的集合的数据发生变化(添加、删除)时才起作用,而在内部数据发生变化时则不起作用。
为了观察内部数据的变化,你必须写
$scope.$watch('items', function(newVal, oldVal) {
console.log(oldVal, newVal);
}, true);
已编辑请参阅此处
https://jsfiddle.net/5bf3v0xj/
为什么
$scope.items = [
{name: 'item1', value: true},
{name: 'item2', value: false},
{name: 'item3', value: true}
];
而不是
$scope.items = {
item1: true},
item2: false},
item3: true}
}
说明
因为ng-repeat
创建它自己的scope
并复制基元值。
字符串表现为原始值,因此ng-repeat
将拥有此变量的它自己的副本。并且因为您>观看原件`而不是复制品,它永远不会火。
还有一件事:在 ng-repeat 变量 中添加 .
是一种很好的风格:
喜欢
代码中的ng-model='item.value
。
关于javascript - $watch 或 $watchCollection 不适用于 ng-repeat 内的 ng-model 引用的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38355946/