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

标签 javascript angularjs

我正在使用 $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/

相关文章:

javascript - 如何在 AngularJS 中切片/trim $scope 变量

javascript - AngularJS Jasmine isolateScope() 返回未定义

javascript - Android 脚本层 - LibGDX

html - Angular 2 : How to show inner HTML of component-tags inside of component?

javascript - 检查页面是否在 Google Chrome 的 Iframe 中

javascript - 使用 Angular 路由 url 格式 #!/issue

javascript - 删除 body 标签 Angular 应用程序的属性

javascript - 在 AngularJS 表达式中调用全局变量

javascript - 如何通过分配点后的最后两位数字将字符串转换为 float ?

javascript - angularjs ng-repeat 实现滚动条