0

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.

Roham Rafii
  • 2,929
  • 7
  • 35
  • 49
Luntegg
  • 2,496
  • 3
  • 16
  • 31
  • @Cerbus Why do you think that other question is similar? There is changes all array, and I need changes only objects in array. – Luntegg Jun 17 '16 at 14:46

2 Answers2

2

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;

Satpal
  • 132,252
  • 13
  • 159
  • 168
1

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>
Hadi J
  • 16,989
  • 4
  • 36
  • 62