$scope.$emit 和 $rootScope.$emit 有什么区别?

What is difference between $scope.$emit and $rootScope.$emit?

$scope.$emit 和 $rootScope.$emit 有什么区别?

我用它从指令发出到控制器,它可以双向工作!

$emit() 在链中向上发送对其 parent 作用域的更改。

因此,当您执行 $scope.$emit 时,您正在向 parent 范围发送通知,它可能是另一个 $scope 或可能是 $rootScope
它基本上像 childScope > parentScope(s).

它的反义词是.broadcast()

.broadcast() 将更改广播到 child 范围。因此,如果您从 $rootScope 广播,那么所有 child $scope 都会收听。


来自文档:

$emit(name, args);

Dispatches an event name upwards through the scope hierarchy notifying the registered $rootScope.Scope listeners.

The event life cycle starts at the scope on which $emit was called. All listeners listening for name event on this scope get notified. Afterwards, the event traverses upwards toward the root scope and calls all registered listeners along the way. The event will stop propagating if one of the listeners cancels it.

Any exception emitted from the listeners will be passed onto the $exceptionHandler service.

当您希望 $scope 及其所有 parents 和 $rootScope 能够听到该事件时,

$scope.$emit 很有用。 $scope.$emit 是 child 对他们 parents $scope 的抱怨。

$rootScope.$emit 只允许其他 $rootScope 听众捕捉它。当您不想通知每个 $scope 时,这很有用。

$scope.$emit 允许当前作用域和父作用域(包括 rootScope)监听一个事件。

$rootScope.$emit 只允许 rootScope 侦听特定事件。