如何遍历对象列表,将监视分配给它们的变量,并使用它们的回调之一?

How can iterate over a list of objects, and assign watches to their variables, and use one of their callbacks?

这是一个完全符合我要求的 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);
  }

有更好的方法吗?

问题:

  1. 如何抑制初始警报?

  2. $scope.$watch('items['+i+']',真的是正确的做法吗?我的意思是它有效,但是......我觉得有某种可怕的性能问题受到威胁。

修改 watch 以查看值是否已更改,并且仅在已更改时调用您的函数

$scope.$watch('items['+i+']', function(newValue, oldValue){
  if(newValue !== oldValue){
    newValue.fn();  
  }    
}, true);

手表很贵,你可以去掉 $watch 并在复选框上使用 ng-change,这样性能会更好

例如

http://jsfiddle.net/qbuLk2gd/

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")})
  ];      
}

简单多了!

DEMO