Angularjs Examples

AJS Examples

AngularJS $scope.$watch() Function

The AngularJS $scope.$watch() method is used to monitor changes in a variable on the $scope. AngularJS scope's $watch method registers a listener callback to be executed whenever the $scope data changes. Once a watcher is configured with the scope, the listener function is called to initialize the watcher. This method is for watching changes of scope variables. This method has callback function which gets called when the watching properties are changed.

The $watch method require three parameters: watchExpression, listener and objectEquality, where listener and equality object are optional parameters.


$scope.$watch(watchExpression, listener, [objectEquality]);
  • In the $watch method watchExpression is the variable or property in the scope to watch. This watchExpression is called on every $digest() and returns the value that is being watched.
  • In the $watch method listener is a function that is called when the value of the $scope property are not equal to previous value. If the watchExpression is equal to previous value then listener will not be called.
  • In the $watch method objectEquality is a boolean type and used for object equality using Anangular.equals instead of comparing for reference equality.

AngularJS $scope.$watch() Function Example

<!DOCTYPE html>        
<head>  <!-- -->       
 <script src="//"></script>         
    <meta charset="utf-8">        
    <title>AngularJS $watch Example</title>        
var app = angular.module('app', []);        
    app.controller("WatchController", function ($scope) {
		$scope.count = 0;
		$scope.Fruit = "Orange";

		$scope.$watch('Fruit', function() {
			$scope.count += 1;
		}, true);
<body style="background-color:#DDE4E9;">        
  <fieldset style="background-color:#DDE4E9;">                    
    <legend>AngulerJS $watch Function Example</legend>         
  <div ng-app="app">              
    <div ng-controller="WatchController"> 
        Scopes Default Value: <input type="text" ng-model="Fruit" />
		<p style="font-family:Arial;color:yellow;background:steelblue;padding:3px;width:350px;">
			Count: {{count}} - {{Fruit}}
See Live Example