Original:
http://yuankeqiang.lofter.com/post/8de51_1454f93 Use $watch to monitor model changes in Angular.js $watch is a
simple
function to use $watch to monitor model changes, when your model changes It will notify you.
$watch(watchExpression, listener, objectEquality);
The description of each parameter is as follows:
watchExpression: the object of the listener, it can be an angular expression such as 'name', or a function such as function(){return $scope.name}.
listener: A function or expression that will be called when watchExpression changes, it receives 3 parameters: newValue (new value), oldValue (old value), scope (reference of scope)
objectEquality: Whether to listen deeply, if set to true , which tells Angular to check for changes to every property in the monitored object. If you want to monitor individual elements of an array or a property of an object instead of a common value, then you should use it.
For example :
$scope.name = ' hello';
var watch = $scope.$watch('name',function(newValue,oldValue, scope){
console.log(newValue);
console.log(oldValue);
});
$timeout(function(){
$scope.name = "world";
},1000);
$watch performance problems
Too many $watches will cause performance problems, if $watch is no longer used, we'd better release it .
The $watch function returns a function to unregister the watch. If we want to watch a property and then unregister it later, we can use the following:
var watch = $scope.$watch('someModel.someProperty', callback);
// ...
watch();
There are also 2 functions related to $watch:
$watchGroup(watchExpressions, listener);
$watchCollection(obj, listener);
angular $watch use
Guess you like
Origin http://10.200.1.11:23101/article/api/json?id=326713060&siteId=291194637
Ranking