【问题标题】:How can iterate over a list of objects, and assign watches to their variables, and use one of their callbacks?如何遍历对象列表,并将手表分配给它们的变量,并使用它们的回调之一?
【发布时间】: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);
  }

有没有更好的方法来做到这一点?

问题:

  1. 如何抑制初始警报?

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

【问题讨论】:

  • 您可以简单地使用 $scope.$watchCollection 来查看数组。在 google 上查找
  • @SmileApplications - 这将观察整个数组,并且不会让我分配单独的回调。
  • 但是您可以检查旧的和新的之间的差异并获取更改的那个...

标签: javascript angularjs watch


【解决方案1】:

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

$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

【讨论】:

  • 好的,这解决了初始位。问题更多的是关于观察每个对象并分配回调的代码。
  • 那么你需要修改问题......这不是你问的,也不清楚你现在问的是什么
  • 至于更好的方法......是的......如果你有很多物品,手表很贵,可以在复选框上使用ng-change并摆脱$watch
  • 是的!这可能是正确的答案!将其编辑到您的答案中,我明天会接受。
猜你喜欢
  • 2023-03-19
  • 1970-01-01
  • 1970-01-01
  • 2022-11-20
  • 2019-01-26
  • 1970-01-01
  • 2021-01-22
  • 1970-01-01
  • 2014-04-20
相关资源
最近更新 更多