Simple overview of AngularJS $watch

AngularJS is being widely used these days, it is used to do in-numerous number of tasks, it is hard for it to keep track of all the elements, so it has to get a way to let few particular elements that needs to be tracked for changes. So Angular has watchers to keep track of all elements that needs to be tracked down, these elements can either be variables, objects, outputs of a functions etc but how to know which ones are to be tracked and which one’s not, this can be done either by using {{varname}} or by associating  the variable with $watch .

Syntax: $scope.$watch(watchExpression, listener);

a)  Where  watchExpression is the expression that needs to be watched, this can be an array or object or function.

b) listener is a function that would be called whenever there is a change in the expression. The listener can be of two types-

i) It can be just a function that have no parameters, this can be

ii) It can have parameters that needs to be compared with a new variable that is created like – syntax:  function(newVar, oldVar)

Examples:

1) When we have a bunch of pink flowers in a vase, we usually check the freshness of flowers from time to time and change the flowers when they have started fading out the color.

angularwatch1

Here, flowers are the watchExpression  and the act of changing flowers is the listener, whenever there is  a change in flowerColor, the changeFlower() is called.

2) When we go to pick Chrysanthemums, we pluck them when they have come for blossom but not in the bud.

angularwatch2

In the above example, blossom is the “new value” and bud is the “old value” of the flowerStage variable, so when flowerstage has been moved from bud to blossom, we perform the action of pluckFlower()

3) When there is a pot of water for certain level let’s say at 10, if the level of water goes down due to sun or any other reason we need to water it else if the level of water goes up we need to take out the extra water. This can be done as follows-

waterlevel

Leave a comment