[英]angular: $watch object in array of objects
For example, I have an array of objects. 例如,我有一个对象数组。
$scope.items = [
{id: 1, name: 'one'},
{id: 2, name: 'two'},
{id: 2, name: 'three'}
];
And have in template something like 并在模板中有类似
<div ng-repeat="item in items">
<input type="text" ng-model="item.name" />
</div>
And I want to add $watch
to this like (for track changes in inputs) 我想像这样添加
$watch
(用于跟踪输入中的更改)
$scope.$watch('item', function(newVal){}, true);
What I need to do, if I want have in newVal
item like {id: 1, name: 'one'}
? 如果我想在
newVal
项目中使用{id: 1, name: 'one'}
类的东西,我该怎么办?
Not array of objects! 没有对象数组! Only one changed object in
newVal
! newVal
只有一个更改的对象! I can't create variables for each object of the array in the controller. 我无法在控制器中为数组的每个对象创建变量。
I tried something like 我尝试了类似的东西
for (var i = 0; i < $scope.items.length; i++) {
$scope.$watch('items[' + i = ']', function(newVal) {
console.log(newVal);
}, true);
}
but that wrong. 但是那是错误的。
You can try something like 您可以尝试类似
for (var i = 0; i < $scope.items.length; i++) {
(function(k){
$scope.$watch(function(){
return $scope.items[k]
}, function(newVal) {
console.log(newVal);
}, true);
})(i);
}
Note: I have not tested the above code; 注意:我尚未测试以上代码;
try this. 尝试这个。
var app = angular .module('MyApp', []) .controller('Main', ['$scope', function($scope) { var vm = this; vm.items = [ {id: 1, name: 'one'}, {id: 2, name: 'two'}, {id: 2, name: 'three'} ]; for (var i = 0; i < vm.items.length; i++) { $scope.$watch('ctrl.items[' + i + ']', function(newVal) { console.log(newVal); }, true); } } ]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div class="main-content" ng-app="MyApp" ng-controller="Main as ctrl"> <div ng-repeat="item in ctrl.items"> <input type="text" ng-model="item.name" /> </div> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.