Angular 没有监听器的 $watch 范围

Angular scope $watch without listener

今天看到一段代码,注册了一个watcher,如下:

scope.$watch(function() { //some code which is not relevant in current context });

Angular 文档将 $watch 方法指定为

$watch(watchExpression, listener, [objectEquality]);

那么watcher没有listener的用法是什么

提前致谢

你不需要表达式你可以使用一个函数来return观察哪个变量,而不是指定它在字符串中,例如:

$scope.myVar = true;

$scope.$watch(function() {
    return $scope.myVar
}, function(newValue, oldValue) {

});
scope.$watch(function() {
    //some code which is not relevant in current context
});

是一种模式,可用于 运行 每个摘要编码一次。相当于:

scope.$watch(function(){
}, undefined);

来自docs

If you want to be notified whenever $digest is called, you can register a watchExpression function with no listener. (Since watchExpression can execute multiple times per $digest cycle when a change is detected, be prepared for multiple calls to your listener.)