VOOZH about

URL: https://www.geeksforgeeks.org/angular-js/how-to-watch-service-variables/

⇱ How to watch service variables ? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to watch service variables ?

Last Updated : 14 Jul, 2022

$scope acts as a built-in object in AngularJs.

It consists of application data and methods. The $scope is acts as a link between a controller and view (HTML).

👁 Image

$scope is used to transfer the data.

$watch:

Scope in AngularJs object has $watch event which comes into picture when the model property gets changed or altered.

When a data binding is created from some point of program in the view to a variable on the $scope object, a watch is created internally in AngularJs.

The digest gets called multiple times, when we $watch() a function.

Every time when we bind the UI, We insert $watch in $watch list.

User: <input type="text" ng-model="user" />
Password: <input type="password" ng-model="pass" />

Example: 

👁 Image
Output

$watch in AngularJs is a service.

It is used to keep the track of the changes on specific properties within a given scope. It is similar to an event listener. e changes are made in the value of specified variables.

When we register a watch we pass two functions as parameters to the $watch() function.These functions are:

  • A value function
  • A listener function

Example:

$scope.$watch(function() {}, //value function
 function() {} //listener function
 );

A watcher can change in responses on:

  1. Timeouts
  2. UI
  3. Complex asynchronous computations performed by web workers
  4. Ajax calls

Methods Used: $scope.$watchGroup

$watchGroup() is a shortcut to set up watchers with the same callback, passing an array of watchExpressions.

$scope.$watchGroup(['obj.a', 'obj.b.bb[4]', 'letters[8]'], function(newValues, oldValues, scope) { //... });

$scope.$watchCollection is a shortcut to watch arrays or objects. In arrays, the listener is called when any of the elements are replaced, deleted, or added.

The $watch keeps track of the variable. This function takes two arguments:

new value 

$scope.$watch('expression', function (newvalue, oldvalue) { //expression parameter //Code });

old value

$scope.$watch(function () {}, function (newvalue, oldvalue) { //Function Parameter // Code });

Example: 

👁 Image
Output

Others:

$digest()

We call the $digest() function when AngularJS thinks it is necessary.

For example, after a button click  handler is executed, or after an AJAX call returns.

$apply():

The $scope.$apply() function takes a function as parameter which it is executed, and after that $scope.$digest() is called internally. That makes it helpful to all the watches are checked

$scope.$apply(function() {
 $scope.data.myVar = "value";
});

Example of $Watch:

CSS: 

👁 Image
Output
Comment
Article Tags:

Explore