AngularJS 模块间的通信 [英] Communication between modules in AngularJS

查看:27
本文介绍了AngularJS 模块间的通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在一个 shellpage 中可能有许多 angular-modules 附加到不同的区域.但是 AngularJS 中的模块可以相互交谈"吗?如果是,如何?

I guess it is possible to have many angular-modules attached to different regions within one shellpage. But can modules in AngularJS "talk" to each other? If yes, how?

推荐答案

模块可以通过多种方式交互或共享信息

There are various ways module can interact or share information

  1. 一个模块可以被注入到另一个模块中,在这种情况下,容器模块可以访问被注入模块的所有元素.如果您查看 angular seed 项目,则会为指令、控制器、过滤器等创建模块像这样

  1. A module can be injected into another module, in which case the container module has access to all elements of the injected module. If you look at angular seed project, modules are created for directive, controllers, filters etc, something like this

angular.module("myApp", ["myApp.filters", "myApp.services", "myApp.directives", "myApp.controllers"])这更像是一种可重用机制,而不是通信机制.

angular.module("myApp", ["myApp.filters", "myApp.services", "myApp.directives", "myApp.controllers"]) This is more of a re usability mechanism rather than communication mechanism.

@Eduard 解释的第二个选项是使用服务.由于服务是单例的并且可以注入任何控制器,因此它们可以充当通信机制.

The second option is as explained by @Eduard would be to use services. Since services are singleton and can be injected into any controller, they can act as a communication mechanism.

正如@Eduard 再次指出的,第三个选项是使用 $scope 对象使用父控制器,因为它可用于所有子控制器.

As @Eduard again pointed out the third option is to use parent controller using $scope object as it is available to all child controllers.

您还可以将 $rootScope 注入需要交互的控制器中,并使用 $broadcast 和 $on 方法创建服务总线模式,其中控制器使用 pub\sub 机制进行交互.

You can also inject $rootScope into controllers that need to interact and use the $broadcast and $on methods to create a service bus pattern where controllers interact using pub\sub mechanism.

我倾向于第四种选择.在此处查看更多详细信息 什么是正确的通信方式AngularJS 中的控制器之间?

I would lean towards 4th option. See some more details here too What's the correct way to communicate between controllers in AngularJS?

这篇关于AngularJS 模块间的通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆