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).

$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:
html
<!DOCTYPE html>
<html>
<head>
<title>
AngularJs $watch() Function with GFG
</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js">
</script>
<script type="text/javascript">
var app = angular.module("watchApp", []);
app.controller("watchCtrl", function ($scope) {
$scope.count = -1;
$scope.$watch(
"txtval", function (newval, oldval) {
$scope.count = $scope.count + 1;
});
});
</script>
</head>
<body>
<div ng-app="watchApp"
ng-controller="watchCtrl">
Enter Text:<input type="text"
ng-model="txtval" />
<br />
<br />
<span style="color: Green;">
$watch() Function Fired: {{count}}</span>
</div>
</body>
</html>
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:
- Timeouts
- UI
- Complex asynchronous computations performed by web workers
- 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:
html
<!DOCTYPE html>
<html>
<head>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.min.js">
</script>
</head>
<body ng-app="myNgApp">
<div ng-controller="myController">
Message: <input type="text"
ng-model="message" />
<br />
New Message: {{newMessage}} <br />
Old Message: {{oldMessage}}
</div>
<script>
var ngApp = angular.module('myNgApp', []);
ngApp.controller('myController', function ($scope) {
$scope.message = "GeeksForGeeks!";
$scope.$watch(
'message', function (newValue, oldValue) {
$scope.newMessage = newValue;
$scope.oldMessage = oldValue;
});
});
</script>
</body>
</html>
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:
html
<div class="container" data-ng-app="app">
<div class="well" data-ng-controller="FooCtrl">
<p><strong>Controller1</strong></p>
<div class="row">
<div class="col-sm-6">
<p><a href=""
ng-click=
"setItems([ { name: 'I am single item' } ])">
Send item one </a></p>
<p><a href=""
ng-click=
"setItems([ { name: 'Item 1 of 2' },
{ name: 'Item 2 of 2' } ])">
Send item two </a></p>
<p><a href=""
ng-click=
"setItems([ { name: 'Item 1 of 3' },
{ name: 'Item 2 of 3' },
{ name: 'Item 3 of 3' } ])">
Send item three </a></p>
</div>
<div class="col-sm-6">
<p><a href=""
ng-click="setName('Sheldon')">
Send name: Geeks</a></p>
<p><a href=""
ng-click="setName('Leonard')">
Send name: For</a></p>
<p><a href=""
ng-click="setName('Penny')">
Send name: Geeks</a></p>
</div>
</div>
</div>
<div class="well"
data-ng-controller="BarCtrl">
<p><strong>Controller2</strong></p>
<p ng-if="name">Name is: {{ name }}</p>
<div ng-repeat="item in items">
{{ item.name }}</div>
</div>
</div>
javascript
var app = angular.module('app', []);
app.factory('PostmanService', function() {
var Postman = {};
Postman.set = function(key, val) {
Postman[key] = val;
};
Postman.get = function(key) {
return Postman[key];
};
Postman.watch = function($scope, key, onChange) {
return $scope.$watch(
function() {
return Postman.get(key);
},
function(newValue, oldValue) {
if (newValue !== oldValue) {
// Only update if the value changed
$scope[key] = newValue;
// Run onChange if it is function
if (angular.isFunction(onChange)) {
onChange(newValue, oldValue);
}
}
}
);
};
return Postman;
});
app.controller('FooCtrl', ['$scope',
'PostmanService',
function($scope, PostmanService) {
$scope.setItems = function(items) {
PostmanService.set('items', items);
};
$scope.setName = function(name) {
PostmanService.set('name', name);
};
}]);
app.controller('BarCtrl', ['$scope',
'PostmanService',
function($scope, PostmanService) {
$scope.items = [];
$scope.name = '';
PostmanService.watch($scope, 'items');
PostmanService.watch(
$scope,'name', function(newVal, oldVal) {
alert('Hi, ' + newVal + '!');
});
}]);
CSS:
css
.well {
margin-top: 10px;
margin-bottom: 10px;
}
p:last-child {
margin-bottom: 0;
}
Output
Similar Reads
How to use $rootScope to store variables in Angular ?
In Angular, the $rootScope is the service that is the top-level for all the controllers in the Angular application. This exists over the entire application lifecycle and can also be used to store the variables that need to be accessed globally. $rootScope is a singleton object that is across the ent
4 min read
How to Manipulate DOM using Service Worker ?
Using a service worker, indirectly manipulates the DOM through communication with the client page it controls. DOM (Document Object Model)In JavaScript, the DOM (document object model) is a programming interface that represents the structure of HTML or XML files as a hierarchical tree shape. It prov
5 min read
How to use services with HTTP methods in Angular v17?
In Angular 17, services play an important role in managing HTTP requests to backend servers. By encapsulating HTTP logic within services, you can maintain clean, modular, and testable code. In this article, we'll explore how to use services to handle HTTP requests effectively in Angular 17 applicati
3 min read
Node.js fs.watchFile() Method
The fs.watchFile() method is used to continuously watch for changes on the given file. It has a callback listener that is called every time the file is accessed. It has an optional options parameter that can be used to specify properties like the interval on how often the file has to be polled and w
4 min read
What is a Webhook and How to Use it?
Webhooks allow interaction between web-based applications through the use of custom callbacks. The use of webhooks allows web applications to automatically communicate with other web-apps. Unlike traditional systems where one system (subject) keeps polling another system (observer) for some data, We
6 min read
Service Workers in Javascript
What is Service Worker: A service worker is a script that runs independently in the browser background. On the user side, it can intercept its network requests and decide what to load (fetch). Service workers mainly serve features like background sync, push notifications and they are commonly used f
5 min read
How to Trigger Watchers on Initialization in Vue.js ?
Vue.js is a popular JavaScript framework used for building user interfaces. One of the main features of vue.js is the reactivity system it helps us in developing data-driven applications i.e. if data changes then the change is reflected on the user interface. In this article, we will see how we can
5 min read
Introduction to Angular Service Worker
A Service Worker is a script that acts as the proxy to the browser network, to enable offline or low connectivity applications. The service worker is available in the form of the @angular/service-worker package that allows to easily integrate service workers into the Angular application.The Angular
5 min read
How to dynamically manage data using variables in Postman?
In this article, we will learn dynamic data management in Postman through the use of variables. Postman, a substantially used API trying out and improvement device, gives a sturdy framework for growing, organizing, and executing API requests. Variables, as key components of Postman's capability, per
4 min read
Vue.js Watchers
A Watcher in Vue.js is a special feature that allows one to watch a component and perform specified actions when the value of the component changes. It is a more generic way to observe and react to data changes in the Vue instance. Watchers are the most useful when used to perform asynchronous opera
3 min read