以this Plnkr为例。我不知道会事先创建多少个fooCollection
成员。因此,我不知道将有多少个bar
模型。
但是我知道它们将成为 Angular 模型,而且我知道它们将在哪里。
我该如何在这些文件上添加$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);
});
});
最佳答案
创建单个列表项 Controller :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>
关于angularjs - 如何在ng-repeat创建的模型上监视变化?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20024156/