0

I have the following variable:

var $scope.abc = [{"a":22,"b":"x"},{"a":33,"b":"y"}];

Is it possible to do a watch on this and watch for just the value of the field a changing?

1 Answer 1

2

Is it possible to do a watch on this and watch for just the value of the field a changing

Sure.

If you want to watch only for value a you can define ng-change for (suppose a is a input) input a.

HTML

<div ng-controller="Controller">
   <div ng-repeat="val in abc">
     <input type='text' ng-model='val.a' ng-change="onAChange(val.a)">
     <input type='text' ng-model='val.b'>
  </div>
 </div>

JS

$scope.onAChange = function(mod){
  console.log(mod);
};

Demo 1 Plunker

Other way, to $watch on all object abc and write "deep" watch, something like:

     $scope.$watch(function () {
       return $scope.abc[0].a;
     },
     function (newValue, oldValue) {
     if(newValue == oldValue){return;}

        console.log(newValue, oldValue);

     }, true);

Demo 2 Plunker

As a side note:

You don't need var before $scope.abc.

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

1 Comment

Thanks for the comment about var. I will remove that, I was just trying to give an example and made a mistake. Can you explain a bit more about ng-change. I have never used that. Also I am not really sure how to code the .$watch. Thanks

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.