Wednesday, October 16, 2013

$watch in Angular Js

Angular Js has a concept called digest cycle, which is nothing but a loop of code during which angular checks throughout the scope to determine any changes to the variables within the scope. So, if you have any variables or objects defined under the $scope, then they are subject to undergo digest cycle.

$scope.myObject etc.

But what really keeps track on these variables inside the digest cycle?

The digest cycle internally calls $watch() function which actually takes care on the changes that occur on the variables under the $scope.
Now if you like your custom code to be run every time a change is occurred on your variables under $scope, you can call $watch() on the variable.
Let us see a small example.
Let my variables under the scope be,
//defining watch on my variable
Alert(“My name is changed”);
//you can add the custom functionality as per your requirement
//I gave just an alert for you to understand at the moment

Now when an event is triggered in your page in which your variable (“myName”) is changed,
Consider a button click event,

$scope.myName=”Albert”; // this change will trigger $scope.$watch() into action
Whenever the value of the variable "myName" under the scope changes the alert defined in the $watch() function gets called.
Like this you can define your custom code as per your requirement that should be triggered onchange of your desired variable.

In this way you can set $watch() on any variable you want and define the custom functionality whenever there is a change on any variable on which $watch is called on.
Hope this helps.

No comments:

Post a Comment