How does Angular $scope.$watch work?
How does Angular $scope.$watch work?
6029-Apr-2023
Updated on 01-May-2023
Home / DeveloperSection / Forums / How does Angular $scope.$watch work?
How does Angular $scope.$watch work?
Aryan Kumar
01-May-2023In AngularJS, $scope.$watch is a method that allows you to monitor changes to a scope variable and take action when the variable changes. The $watch method takes two arguments: the name of the variable to watch, and a callback function that is executed when the variable changes.
Here's an example of how to use $scope.$watch in an AngularJS controller:
In this example, $scope.count is the variable that we want to watch for changes. We pass 'count' as the first argument to $scope.$watch. The second argument is a callback function that takes two arguments: newValue and oldValue. This function is executed whenever the value of $scope.count changes, and it logs a message to the console with the old and new values of the variable.
When $scope.$watch is called, it creates a watcher object that is associated with the scope variable that is being watched. This watcher object is stored internally by AngularJS, and it is updated whenever the value of the scope variable changes. When the watcher object is updated, it triggers the callback function that was passed as the second argument to $scope.$watch.
Note that $scope.$watch can be a performance bottleneck if it is used to monitor a large number of variables or if the callback function is complex. In such cases, it is better to use $scope.$watchGroup or $scope.$watchCollection, which are optimized for watching groups of variables or collections of objects, respectively.