0
$scope.testObj={};
angular.forEach(results, function (value,index) {
$scope.testObj[index]=value.arr;

console.log($scope.testObj[index]);
console.log(index);
$scope.$watch('testObj',function(newVal, oldVal) {       
        console.log(newVal, oldVal) ;  
      },true
);
})

The above code works fine (do not worry about results;it is an array). The problem lies when I am trying that:

$scope.$watch('testObj[index]',function(newVal, oldVal) {       
            console.log(newVal, oldVal) ;  
          },true
    );

I have no idea why that happens and I am getting undefined from both newVal, oldVal. How may I solve that?

By the way testObj[0] works...

3
  • why dont you assign to a object and do? Commented Dec 21, 2016 at 16:10
  • What exactly do you mean? It is not clear at all Commented Dec 21, 2016 at 16:16
  • you are trying to pass w variable index to a function arguments, what do you expect bro ? Commented Dec 21, 2016 at 16:18

3 Answers 3

2

Try this,

$scope.myvar = testObj[index];
$scope.$watch('myvar',function(newVal, oldVal) {       
            console.log(newVal, oldVal) ;  
          },true
);

EDIT

If you render change your array in ng-repeat, you can to use ng-change directive and pass in it $index parameter.

<div ng-repeat="arr in myvar">
   <input type="text" ng-model="arr.location" ng-change="changeValue($index)"/>
</div>

or use a loop and access using its index

$scope.$watch('myvar', function (newValue, oldValue) {
   for(var i = 0; i < newValue.length; i++) {

   }
}, true);
Sign up to request clarification or add additional context in comments.

2 Comments

However, I want to keep track of all the arrays: testObj[0], testObj[1] ... The above won't do my job
I am not using the view for that, only the controller. Is there any way for $scope.$watch to understand the first argument the way I want?
0

$watchGroup can come to your need more doc https://docs.angularjs.org/api/ng/type/$rootScope.Scope

Comments

0

You got the other way round. Because forEach only executed once, the $watchers inside will only watch it once and then was tore down. What you need to do is watch the collection, then put your forEach insde.

$scope.$watch('testObj', function(newVal, oldVal) {
  angular.forEach(newVal, function(value, index) {
    $scope.testObj[index] = value.arr;
    console.log($scope.testObj[index]);
    console.log(index);
  })
}, true);

Comments

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.