$watch - Watchers in AngularJS

Watchers are used in AngularJs to check if the value of a model has been changed; if yes then take some appropriate action. To check the value of the model we use the $watch() method provided inside the $scope object. 
  1. angular.module('MyFirstModule',[]).controller('MyFirstController',function($scope){    
  2.    $scope.salary='25000';    
  3.        
  4.    $scope.$watch('salary',function(newSalary,oldSalary){    
  5.       console.log("There has been change in your salary");    
  6.    }    
  7. });  
The first parameter inside the $watch() is the name of the model which we need to monitor for change.
 
The second parameter is a callback function which accepts two values, first value is the new value of the model which we are monitoring and second one is the old value. The second parameter (old value) is optional and can be skipped. 
Ebook Download
View all
Learn
View all