如何$观察由ng-repeat创建的模型的变化?

时间:2013-11-16 21:30:16

标签: angularjs angularjs-scope angularjs-ng-repeat

例如考虑this Plnkr。我不知道会预先创建多少fooCollection个成员。所以我不知道会有多少bar个模型存在。

但我知道他们将成为角模型,我知道他们将会在哪里。

如何对这些进行$watch

我需要这样做,因为我需要在更改bar模型时触发行为。仅仅观察fooCollection本身是不够的,$watch监听器在bar被更改时不会触发。

相关的html:

<body ng-controller="testCtrl">
  <div ng-repeat="(fooKey, foo) in fooCollection">
    Tell me your name: <input ng-model="foo.bar">
    <br />
    Hello, my name is {{ foo.bar }}
  </div>
  <button ng-click="fooCollection.push([])">Add a Namer</button>
</body>

相关JS:

angular
.module('testApp', [])
.controller('testCtrl', function ($scope) {
  $scope.fooCollection = [];

  $scope.$watch('fooCollection', function (oldValue, newValue) {
    if (newValue != oldValue)
      console.log(oldValue, newValue);
  });
});

6 个答案:

答案 0 :(得分:34)

创建单独的列表项控制器:demo on Plnkr

JS

angular
  .module('testApp', [])
  .controller('testCtrl', function ($scope) {
    $scope.fooCollection = [];
  })
  .controller('fooCtrl', function ($scope) {
    $scope.$watch('foo.bar', function (newValue, oldValue) {
      console.log('watch fired, new value: ' + newValue);
    });
  });

HTML

<html ng-app="testApp">
  <body ng-controller="testCtrl">
    <div ng-repeat="(fooKey, foo) in fooCollection" ng-controller="fooCtrl">
      Tell me your name: <input ng-model="foo.bar" ng-change="doSomething()">
      <br />
      Hello, my name is {{ foo.bar }}
    </div>
    <button ng-click="fooCollection.push([])">Add a Namer</button>
  </body>
</html>

答案 1 :(得分:9)

如果您已经填充了您的集合,则可以在ng-repeat的每个项目上放置一个监视:

<强> HTML

<div ng-repeat="item in items">
   {{ item.itemField }}
</div>

<强> JS

for (var i = 0; i < $scope.items.length; i++) {
   $scope.$watch('items[' + i + ']', function (newValue, oldValue) {
      console.log(newValue.itemField + ":::" + oldValue.itemField);
   }, true);
}

答案 2 :(得分:5)

您可以将true作为第三个参数传递给$ watch

$scope.$watch('something', function() { doSomething(); }, true);

https://docs.angularjs.org/api/ng/type/$rootScope.Scope

答案 3 :(得分:3)

您还可以创建一个自定义指令,告诉主控制器进行更改

YourModule.directive("batchWatch",[function(){
return {
    scope:"=",
    replace:false,
    link:function($scope,$element,$attrs,Controller){
        $scope.$watch('h',function(newVal,oldVal){
            if(newVal !== oldVal){
              Controller.updateChange(newVal,oldVal,$scope.$parent.$index);
            }

        },true);

    },
    controller:"yourController"
};
}]);

假设你的标记是这样的

<ul>
  <li ng-repeat="h in complicatedArrayOfObjects">
      <input type="text" ng-model="someModel" batch-watch="$index" />
  </li>
</ul>

这是你的控制器

YourModule.controller("yourController",[$scope,function($scope){
    this.updateChange = function(newVal,oldVal,indexChanged){
      console.log("Details about the change");
    }
}]);

您还可以使用指令链接函数提供的值,该函数位于前3个参数,scope,element和attr。

答案 4 :(得分:2)

由于我不想要另一个控制器,我最终使用了ng-change

简单的jsFiddle:https://jsfiddle.net/maistho/z0xazw5n/

相关HTML:

<body ng-app="testApp" ng-controller="testCtrl">
    <div ng-repeat="foo in fooCollection">Tell me your name:
        <input ng-model="foo.bar" ng-change="fooChanged(foo)">
        <br />Hello, my name is {{foo.bar}}</div>
    <button ng-click="fooCollection.push({})">Add a Namer</button>
</body>

相关JS:

angular.module('testApp', [])
    .controller('testCtrl', function ($scope) {
    $scope.fooCollection = [];

    $scope.fooChanged = function (foo) {
        console.log('foo.bar changed, new value of foo.bar is: ', foo.bar);
    };
});

答案 5 :(得分:0)

尝试这样做

 <div ng-repeat="foo in fooCollection" ng-click="select(foo)">Tell me your ame:
        <input ng-model="foo.bar" ng-change="fooChanged(foo)">
        <br />Hello, my name is {{foo.bar}}</div>
        <button ng-click="fooCollection.push({})">Add a Namer</button>
 </div>

指令/控制器中有代码

 $scope.selectedfoo = {};
 $scope.select = (foo) => {
    $scope.selectedfoo = foo;
 }

 $scope.$watch('selectedfoo ', (newVal, oldVal) => {
  if (newVal) {

  }
 },true)