【发布时间】:2016-01-13 06:20:38
【问题描述】:
这是一个完全符合我要求的 jsfiddle:http://jsfiddle.net/4evvmqoe/1/ (除了那些初始警报......有没有办法抑制那些?)。
HTML:
<div ng-app="">
<div ng-controller="MyCtrl">
<div ng-repeat = "x in items">
<input type = "checkbox" ng-model = "x.bool"/>
{{x.label}}
</div>
</div>
</div>
JS:
function MyCtrl($scope) {
var CheckBox = function(label, fn){
this.label = label;
this.fn = fn;
this.bool = true;
}
$scope.items = [
new CheckBox("aaaa", function(){alert("aaa")}),
new CheckBox("bbbb", function(){alert("bbb")}),
new CheckBox("cccc", function(){alert("ccc")})
];
for (var i = 0; i< $scope.items.length; i++){
$scope.$watch('items['+i+']', function(newValue, oldValue){
newValue.fn();
}, true);
}
}
我关心的是我做手表的代码:
for (var i = 0; i< $scope.items.length; i++){
$scope.$watch('items['+i+']', //<-- seriously?
function(newValue, oldValue){
newValue.fn();
}, true);
}
有没有更好的方法来做到这一点?
问题:
如何抑制初始警报?
$scope.$watch('items['+i+']',真的是正确的做法吗?我的意思是它有效,但是......我觉得存在某种可怕的性能问题。
【问题讨论】:
-
您可以简单地使用 $scope.$watchCollection 来查看数组。在 google 上查找
-
@SmileApplications - 这将观察整个数组,并且不会让我分配单独的回调。
-
但是您可以检查旧的和新的之间的差异并获取更改的那个...
标签: javascript angularjs watch