Hi rani,
In angularjs $watch() function is used to watch the changes of variables in $scope object. Generally the $watch() function will create internally in angularjs to handle variable changes in application.
Suppose in your angularjs applications if you want to create custom watch for some actions then it's better to use $scope.watch function.
To use $scope.watch() function in angularjs you need to pass two parameters one is expression / function and second one is listener function.
Syntax of AngularJS $watch() Function
$watch() function with expression parameters
$scope.$watch('expression', function (newvalue, oldvalue) {
// Your Code
});
$watch() function with function parameters
$scope.$watch(function () {}, function (newvalue, oldvalue) {
// Your Code
});
Example:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module("MyApp", []);
app.controller("MyController", function ($scope) {
$scope.Name = "";
$scope.Count = 0;
$scope.$watch("Name", function (newValue, oldValue) {
if (newValue.length > 0) {
$scope.OldName = "Old name was : " + oldValue;
$scope.NewName = "New name is : " + newValue;
$scope.Count = $scope.Count + 1;
} else {
$scope.Count = 0;
}
});
});
</script>
<div ng-app="MyApp" ng-controller="MyController">
Name: <input type="text" ng-model="Name" /><br />
<span style="color: Red">No. of $watch() function fired: {{Count}}</span><br />
<span style="color: green">{{OldName}}</span><br />
<span style="color: green">{{NewName}}</span>
</div>
</body>
</html>
Demo