gpt4 book ai didi

javascript - 需要知道事件如何在 angularJS 中的同级 Controller 之间传递

转载 作者:行者123 更新时间:2023-11-28 07:35:53 25 4
gpt4 key购买 nike

我知道广播和发出事件的发生方式如下:广播:从父级到子级(从上到下)

<div ng-controller='ctrl1'>

<div ng-controller='ctrl2'>

<div>
</div>
  1. 要从 ctrl2 到 ctrl1 进行通信,使用发射,

  2. 要从 ctrl1 到 ctrl2 进行通信,使用广播,

那么当没有嵌套类型的 Controller 时,我的意思是有路由时,事件是如何传递的

$routeProvider.when(..., Controller :ctrl)

$routeProvider.when(..., Controller : ctr2)

以及这种结构之间的通信是如何发生的。

<div ng-controller='ctrl1'>

<div ng-controller='ctrl2'>

<div>
<div ng-controller='ctrl3'>

<div>
</div>

希望我的许多观点都是有效且有意义的,

请给我解释一下。以及答案,非常感谢

最佳答案

从 Angular 来看 Documentation :

$广播:

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.

$emit:

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 向层次结构向下发送消息,并且无法取消,而 $emit 发送消息向上层次结构,并且可以取消。

如果是 sibling ,一种选择是$emit 父级正在监听的消息,让父级取消该事件,然后$broadcast 向 sibling 发送消息正在听。

但是,一般来说,如果您能够尽可能完全消除 $broadcast$emit 的使用,您会发现您的代码更易于测试和维护,也许通过使用共享服务。

关于javascript - 需要知道事件如何在 angularJS 中的同级 Controller 之间传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28606796/

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