我正在阅读有关范围方法$watch
here的文档。该方法接受:
$watch(watchExpression, [listener]
;
然后他们提供了例子:
// let's assume that scope was dependency injected as the $rootScope
var scope = $rootScope;
scope.name = 'misko';
scope.counter = 0;
expect(scope.counter).toEqual(0);
scope.$watch('name', function(newValue, oldValue) {
scope.counter = scope.counter + 1;
});
expect(scope.counter).toEqual(0);
scope.$digest();
// the listener is always called during the first $digest loop after it was registered
expect(scope.counter).toEqual(1);
scope.$digest();
// but now it will not be called unless the value changes
expect(scope.counter).toEqual(1);
scope.name = 'adam';
scope.$digest();
expect(scope.counter).toEqual(2);
// Using a listener function
var food;
scope.foodCounter = 0;
expect(scope.foodCounter).toEqual(0);
scope.$watch(
// This is the listener function --------- WHY ?????????????
function() { return food; },
// This is the change handler ---- THIS SHOULD BE A LISTNER FUNCTION
function(newValue, oldValue) {
if ( newValue !== oldValue ) {
// Only increment the counter if the value changed
scope.foodCounter = scope.foodCounter + 1;
}
}
);
// No digest has been run so the counter will be zero
expect(scope.foodCounter).toEqual(0);
// Run the digest but since food has not changed count will still be zero
scope.$digest();
expect(scope.foodCounter).toEqual(0);
// Update food and run digest. Now the counter will increment
food = 'cheeseburger';
scope.$digest();
expect(scope.foodCounter).toEqual(1);
我不理解的是,如果这是function() { return food; }
// This is the listener function
的函数,他们在第二个示例中将should return the value that will be watched.
称为watchExpression
的原因?
答案 0 :(得分:1)
评论有点误导,您可能会提出问题或提出改进请求。
正如你所说,$watch(watchExpression, [listener])
watchExpression
每次调用$ digest()时都会调用watchExpression,并且应该返回将要监视的值
监视表达式可以是string
或function
。
如果你指定一个函数,这是一个不的监听器,而是一个多次调用的比较函数,所以不要在这里做任何花哨的东西;)
该比较功能用于角度脏检查
关于这方面的更多细节可以在angularJs的创建者的视频的这一部分中找到:https://www.youtube.com/watch?feature=player_detailpage&v=ZhfUv0spHCY#t=1988
listener
只要watchExpression
的值发生变化,就会调用此函数
因此,这是更新模型和实现业务逻辑的理想场所