gpt4 book ai didi

javascript - $rootScope.$emit 是否向所有 Controller (包括它自己)广播?

转载 作者:行者123 更新时间:2023-12-03 09:33:14 25 4
gpt4 key购买 nike

我正在使用 $rootScope.$emit()$rootScope.$on()在我的 Angular 应用程序中广播和监听状态变化。

在某些情况下,多个 Controller 可以同时发出和监听相同的事件。如果我在同一个 Controller 中有以下代码,这个 Controller 会运行它的.$on吗?发出事件时的代码,还是事件仅广播给其他 Controller ?

$rootScope.$emit('adminChanged');
...
$rootScope.$on('adminChanged', function() {
getCustomerInfo();
});

最佳答案

angular docs答案:(强调我的)

在 $emit 上:

$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.



在 $broadcast 上:

$broadcast(name, args); Dispatches an event name downwards to all child scopes (and their children) notifying the registered $rootScope.Scope listeners.

The event life cycle starts at the scope on which $broadcast was called. All listeners listening for name event on this scope get notified. Afterwards, the event propagates to all direct and indirect scopes of the current scope and calls all registered listeners along the way. The event cannot be canceled.



(另外,请注意 rob 关于使用哪一个的评论!)

关于javascript - $rootScope.$emit 是否向所有 Controller (包括它自己)广播?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31947835/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com