Sam
Sam

Reputation: 14586

angularjs: $watch not triggered

trying to do something simple here.

In my controller:

  $scope.testObject = { name : 'john' };

  $scope.$watch('$scope.testObject.name', function (e, n, v) {
      console.log('reached');
  });

In my view:

  <input type="text"  ng-model="testObject.name"/>

The textbox is bound to the testObject's name property and when the controller is loaded, the code goes into the $watch function.

Now, if I edit the textbox value, the $watch function is never triggered. Why is that ?

I've also tried setting the third argument of $watch to true, with no effects.

Upvotes: 0

Views: 1499

Answers (2)

EpokK
EpokK

Reputation: 38092

Use this:

$scope.$watch('testObject.name', function(e,n,v){
    console.log("reached");
});

You can also add other observer like this:

$scope.$watch('testObject.attr1 + testObject.attr2', function(e,n,v){
    console.log("reached");
});

or:

$scope.$watch('testObject', function(e,n,v){
    console.log("reached");
}, true);

Upvotes: 1

MBielski
MBielski

Reputation: 6620

Remove the $scope from your watch. It should read as:

$scope.$watch('testObject.name', function(e,n,v){
    console.log("reached");
});

Upvotes: 4

Related Questions