Fracedo
Fracedo

Reputation: 626

How to watch this variable in angularjs

I couldn't figure out how to watch a variable that binded to this variable in angularjs.

Here is what I have tried.

in html,

<input type="text" ng-model="vm.text"/>--{{vm.text}}--
    <p>{{vm.count}} times changed</p>
    <input type="text" ng-model="text1"/>--{{text1}}--
    <p>{{count1}} times changed</p>

in app.js

$scope.$watch('this.text', function() {
    console.log('watch 1');
    this.count=this.count+1;
});

$scope.$watch('text1', function() {
// do something here
   console.log('watch 2');
   $scope.count1=$scope.count1+1;
});

and plunker link for the same.

I could watch text1 but I couldn't watch text1.

Can anyone please explain me how to watch text1?

thanks in advance

Upvotes: 0

Views: 2004

Answers (3)

Mateusz Curyło
Mateusz Curyło

Reputation: 46

You have got some separate concerns here.

You are using $scope.watch with controller as syntax. It is not a simple text, here is a fine text about it:

http://www.bennadel.com/blog/2852-understanding-how-to-use-scope-watch-with-controller-as-in-angularjs.htm

and here is my fork of your plunker:

http://plnkr.co/edit/ctDjs0dwe50kMu61TfCW?p=preview

What I did is:

/*make this (controller) callable 
 *from inside my watch function, 
 *so I can observe it and count can change
 */
var vm = this; 

//vm is observable as it is assigned
$scope.$watch(function (scope) {return vm.text;}, 


function() {
   console.log('watch 1');
  //count can change, as the controller is assigned to variable
   vm.count=vm.count+1;       
});

It is a funny situation in which scope can help not only by making watch smoothly callable, but also by being easily referenced from inside watch function ($scope.watch).

Upvotes: 0

Pankaj Parkar
Pankaj Parkar

Reputation: 136144

You need to first bind this context to angular $scope using angular.bind

$scope.$watch(angular.bind(this, function () {
  return this.text;
}), function (newVal) {
  console.log('watch 1');
  this.count=this.count+1;
});

Or place a function inside watcher instead of string & that will get evaluated on each digest cycle

$scope.$watch(function () {
   return vm.text;
},function(value){
   console.log('watch 1');
   this.count=this.count+1;
});

Upvotes: 3

jonasnas
jonasnas

Reputation: 3580

You need to watch vm.text

http://plnkr.co/edit/ctDjs0dwe50kMu61TfCW?p=preview

$scope.$watch('vm.text', function() {
       console.log('watch 1');
             this.count=this.count+1;

   });

Upvotes: 1

Related Questions