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.

1
  • @Cerbus Why do you think that other question is similar? There is changes all array, and I need changes only objects in array. Commented Jun 17, 2016 at 14:46

2 Answers 2

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;

Sign up to request clarification or add additional context in comments.

Comments

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>

1 Comment

this is only value, not all object

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.