如何在ng-repeat创建的模型上监视变化?

阿迪亚议员

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

但是我知道它们将成为角度模型,而且我知道它们将在哪里。

我该如何$watch处理这些?

我需要这样做,因为我需要在bar更改模型时触发行为仅仅观察fooCollection本身是不够的,更改$watcha时侦听器不会触发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);
  });
});
kapv89

创建单个列表项控制器: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>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章