1

What is the purpose of $watch in angularjs. Can anyone explain me how it works and what is the purpose of $watch. Thanks in advance

  • 1
    Its purpose is to watch values, and then act on the variables changes through a callback – devqon Jun 06 '16 at 09:39
  • 4
    possible duplicate for http://stackoverflow.com/questions/15112584/using-scope-watch-and-scope-apply-in-angularjs – Irshu Jun 06 '16 at 09:42
  • What is the question? (I cannot see any question mark at end of your sentences.) – Mityu Apr 27 '22 at 14:41

2 Answers2

4

The $scope.watch() function creates a watch of some variable. When you register a watch you pass two functions as parameters to the $watch() function:

  1. A value function
  2. A listener function

Here is an example:

$scope.$watch(function() {},
              function() {}
             );

The first function is the value function and the second function is the listener function.

The value function should return the value which is being watched. AngularJS can then check the value returned against the value the watch function returned the last time. That way AngularJS can determine if the value has changed. Here is an example:

$scope.$watch(function(scope) { return scope.data.myVar },
              function() {}
             );

This example valule function returns the $scope variable scope.data.myVar. If the value of this variable changes, a different value will be returned, and AngularJS will call the listener function.

The listener function should do whatever it needs to do if the value has changed. Perhaps you need to change the content of another variable, or set the content of an HTML element or something. Here is an example:

$scope.$watch(function(scope) { return scope.data.myVar },
              function(newValue, oldValue) {
                  document.getElementById("").innerHTML =
                      "" + newValue + "";
              }
             );

This example sets the inner HTML of an HTML element to the new value of the variable, embedded in the b element which makes the value bold. Of course you could have done this using the code {{ data.myVar }, but this is just an example of what you can do inside the listener function.

Hope help ful to you.

Kumar Ramalingam
  • 349
  • 3
  • 15
  • "first function" can to be specified by string in called scope. `$scope.$watch('data.myVar', ...)` – vp_arth Jun 06 '16 at 09:48
  • There is no any "b element" in your code. And why are parameters "newValue, oldValue" in fhe second function, if you use inly the newValue? – Mityu Apr 27 '22 at 14:44
0

Take a look at the Angular docs, they are generally pretty good and include examples.

$watch(watchExpression, listener, [objectEquality]);

Registers a listener callback to be executed whenever the watchExpression changes.

https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$watch

Ant Kennedy
  • 1,230
  • 7
  • 13