这是一个 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);
}
}
我关心的是我做 watch 的代码:
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.$watch('items['+i+']', function(newValue, oldValue){
if(newValue !== oldValue){
newValue.fn();
}
}, true);
watch 很昂贵,您可以摆脱 $watch
并在复选框上使用 ng-change
,这样性能会更高
例如。
HTML:
<div ng-app="">
<div ng-controller="MyCtrl">
<div ng-repeat = "x in items">
<input type = "checkbox" ng-model = "x.bool" ng-change = "x.fn()"/>
{{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")})
];
}
简单多了!
关于javascript - 如何迭代对象列表,并将监视分配给它们的变量,并使用它们的回调之一?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34739168/