$watch in AngularJS

12 Jun by vichu

$watch in AngularJS

Reading Time: 3 minutes

A watcher monitors model changes and takes action in response. The $scope object has a function $watch() that’s used to register a watcher. Let’s modify our previous snippet. We want to give users the ability to add a book to their wish list. But once they add two books to their wish list we want to show a congratulatory message. So, we can keep a counter and, each time the user clicks on Add to wishlist link, we will increment this counter by one. But how do we know when the counter reaches two? This is where watchers help us. We can set up a watcher on the counter model to notify us when the value changes. So, if its value is two then we fire an alert. The modified HTML for this is shown below:

See the Pen AngularJS Watch 1 by Vishal Srinivasan (@vishal_srini) on CodePen.0

Note that I’m only showing for the sake of brevity. Then our controller BookController can be modified as following:

See the Pen AngularJS Watch 1 by Vishal Srinivasan (@vishal_srini) on CodePen.0

We added a new model wishListCounter to the BookController scope. Each time user clicks Add to wishlist link $scope.hide() gets called, incrementing the model by one. Now let’s get to the interesting part—setting up a watcher. $scope.watcher() is whatyou need to dothis. The first parameter is watchExpression.This can be the model under watch or a function. The second parameter is a callback function that’s called whenever AngularJS detects a change in the model value or the return value of the passed function. This callback takes two parameters. The first is the new value of the model, while the second is the old value. If you’re interested only in the new value you can skip the second parameter. Now inside the watch callback (also called listener function) we check to see if the newValue is two. If it is we show an alert. We also have a console.log() so we can see how many times the listener function gets called. The Listener is Called Immediately When you load the page you’ll find that the listener function is called immediately. This may seem a little odd, but AngularJS executes the listener function as soon as the watcher is registered. If you don’t want this to happen, you can insert an additional check to see if the newValue and oldValue are same. If that’s the case, then this will be the first time the listener is called as a part of initialization. You can write something like this:

$scope.$watch('someModel',function(newValue,oldValue){
 if(newValue!=oldValue){
 //do something
 }
});

However, the second parameter to $watch() is optional. But, why would anyone want to have a watcher without a listener? We’ll discuss that in the next section. The $watch() function also accepts an optional third parameter objectEquality. In this case we’re watching a simple String. But sometimes you may need to watch an object for change. We want to be notified whenever any of the object’s properties changes. In that case the above code won’t work because AngularJS will compare the objects by reference. To make this work we can pass true as the third argument to $watch() function. This will compare individual properties of the object under watch and call our listener in case of mutation.

Unbinding a Watcher

The return value of $scope.$watch() is a function which can be used to unbind the watcher when needed. This is important because it clears the memory alloted to the watcher. So, after showing the alert if you want to unbind the watcher you can utilize this return value. The corresponding code is:

var unbindWatcher=$scope.$watch('wishListCount',function(newValue,oldValue){
 console.log('called '+newValue+' times');
 if(newValue==2){
 alert('Great! You have 2 items in your wish list. Time to buy what you love. ');
 unbindWatcher();
 }
 

});

Byvichu

Love to code and Love to learn. A passionate technology lover who likes to sit with laptop even for weeks :D

9 Comments

  1. hello there and thank you for your information – I have definitely picked up anything new from right here. I did however expertise some technical issues using this web site, since I experienced to reload the web site lots of times previous to I could get it to load correctly. I had been wondering if your web host is OK? Not that I’m complaining, but slow loading instances times will often affect your placement in google and could damage your quality score if advertising and marketing with Adwords. Anyway I am adding this RSS to my email and can look out for a lot more of your respective intriguing content. Make sure you update this again soon.

  2. Great post. I used to be checking constantly this blog and I’m inspired! Very helpful information specially the last phase 🙂 I maintain such information much. I used to be looking for this particular information for a very long time. Thank you and best of luck.

  3. After looking into a handful of the blog articles on your web site, I honestly like your technique of writing a blog. I saved as a favorite it to my bookmark website list and will be checking back soon. Take a look at my website too and let me know how you feel.

  4. I am not positive the place you are getting your information, however great topic. I must spend some time studying much more or understanding more. Thanks for wonderful info I was looking for this info for my mission.

  5. It’s appropriate time to make some plans for the future and it’s time to be happy. I have read this post and if I could I wish to suggest you some interesting things or tips. Perhaps you could write next articles referring to this article. I wish to read more things about it!

Leave a Reply

Your email address will not be published. Required fields are marked *