Reputation: 2556
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)
$scope.$watch('item', function(newVal){}, true);
What I need to do, if I want have in newVal
item like {id: 1, name: 'one'}
?
Not array of objects! Only one changed object in 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.
Upvotes: 0
Views: 107
Reputation: 17289
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>
Upvotes: 1
Reputation: 133403
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;
Upvotes: 2