在 angularjs 上收听特定范围

Listen to a specific scope on angularjs

在 vanilla 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;
    }
  }
);