Adi*_*M P 41 angularjs angularjs-scope angularjs-ng-repeat
以这个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>
Run Code Online (Sandbox Code Playgroud)
相关JS:
angular
.module('testApp', [])
.controller('testCtrl', function ($scope) {
$scope.fooCollection = [];
$scope.$watch('fooCollection', function (oldValue, newValue) {
if (newValue != oldValue)
console.log(oldValue, newValue);
});
});
Run Code Online (Sandbox Code Playgroud)
kap*_*v89 34
创建单独的列表项控制器:在Plnkr上演示
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);
});
});
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)
如果您填充了您的集合,则可以在ng-repeat的每个项目上放置一个监视:
HTML
<div ng-repeat="item in items">
{{ item.itemField }}
</div>
Run Code Online (Sandbox Code Playgroud)
JS
for (var i = 0; i < $scope.items.length; i++) {
$scope.$watch('items[' + i + ']', function (newValue, oldValue) {
console.log(newValue.itemField + ":::" + oldValue.itemField);
}, true);
}
Run Code Online (Sandbox Code Playgroud)
您可以将true作为第三个参数传递给$ watch
$scope.$watch('something', function() { doSomething(); }, true);
Run Code Online (Sandbox Code Playgroud)
https://docs.angularjs.org/api/ng/type/$rootScope.Scope
| 归档时间: |
|
| 查看次数: |
34571 次 |
| 最近记录: |