在香草JS中,我可以监听特定DOM元素的事件,比如el.addEventListener('click',function(){});
。有没有一种等效的方法可以使用angularjs上的$on方法,并监听特定的范围?
如果您想监听特定的范围值,我建议您使用Angular的$method服务。
以下是如何使用它的示例:
scope.$watch('name', function(newValue, oldValue) {
scope.counter = scope.counter + 1;
});
还有:
scope.$watch(
// This function returns the value being watched. It is called for each turn of the $digest loop
function() { return food; },
// This is the change listener, called when the value returned from the above function changes
function(newValue, oldValue) {
if ( newValue !== oldValue ) {
// Only increment the counter if the value changed
scope.foodCounter = scope.foodCounter + 1;
}
}
);