$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: The 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 monitored object. 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. If $watch is no longer used, we'd better release 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 is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.