SoFunction
Updated on 2025-04-04

Detailed explanation of the event method of angular monitoring data model changes $watch

$watch is simple to use

$watch is a scope function that listens for model changes, which will notify you when parts of your model change.

$watch(watchExpression, listener, objectEquality);

The description of each parameter is as follows:

watchExpression: The object to listen for, it can be an angular expression such as 'name', or a function such as function(){return $}.

listener: a function or expression that will be called when the watchExpression changes. It receives 3 parameters: newValue (new value), oldValue (old value), scope (reference to scope)

objectEquality: Whether to listen deeply, if set to true, it tells Angular to check the changes in each property in the object being monitored. If you want to monitor individual elements of the array or the property of the object instead of a normal value, then you should use it

Take a chestnut:

$ = 'hello';
 
var watch = $scope.$watch('name',function(newValue,oldValue, scope){
  (newValue);
  (oldValue);
});
 
 
$timeout(function(){
  $ = "world";
},1000);

$watch performance issues

Too much $watch will cause performance problems, and if the $watch is no longer used, we'd better free it.

The $watch function returns a function that logs out the listener. If we want to monitor a property and then logs out later, we can use the following method:

var watch = $scope.$watch('', callback);
//...
watch();

There are 2 functions related to $watch:

$watchGroup(watchExpressions, listener);
$watchCollection(obj, listener);

The above detailed explanation of the $watch event method for angular monitoring data model changes is all the content I share with you. I hope you can give you a reference and I hope you can support me more.