Luntegg Luntegg - 5 months ago 52
AngularJS Question

anular: $watch object in array of objects

For example, I have 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 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 array in 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.

Answer

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;

Comments