简体   繁体   English

Angular.js命名间隔模块控制器

[英]Angular.js namespacing modules controllers

I have following structure in my application directory: 我的应用程序目录中具有以下结构:

scripts/
   modules/
     module1/
       controllers/
          MainController.js
     module2/
       controllers/
          MainController.js
   main.js

What I want to achieve is to put controllers in each module to its own namespace, for example: 我要实现的是将每个模块中的控制器置于其自己的名称空间,例如:

module1.MainController
module2.MainController

So when i use in html ng-controller="MainController" directive it knows from which module to serve it. 因此,当我在html ng-controller="MainController"指令中使用它时,它将知道从哪个模块为其提供服务。 Also it would be good that modules can communicate with each other. 模块之间可以相互通信也很好。

Please explain to me how I can achieve this in the best way as possible, and if it's at all possible? 请向我解释我如何才能以最佳方式实现这一目标,如果可能的话?


I've found something like this: http://jsfiddle.net/luisperezphd/j5jzsppv/ but I'm not sure if this is good solution. 我发现了这样的东西: http : //jsfiddle.net/luisperezphd/j5jzsppv/,但是我不确定这是否是一个好的解决方案。 It uses angular.ng-modules.js . 它使用angular.ng-modules.js


EDIT: I'm trying to use Angular.js v.1.3.6. 编辑:我正在尝试使用Angular.js v.1.3.6。 On version 1.2.x there is no problem with namespaces. 在1.2.x版本上,名称空间没有问题。

Inject one of the modules into the other using regular dependency injection: 使用常规依赖项注入将一个模块注入另一个模块:

var moduleTwo = angular.module('moduleTwo', ['otherModule']);

This allows moduleTwo to have awareness of otherModule . 这允许moduleTwo知道otherModule Then you can use a service to share state between controllers. 然后,您可以使用服务在控制器之间共享状态。 Services are singletons (only one instance will exist), so if multiple controllers use the same service they will share that state. 服务是单例(仅存在一个实例),因此,如果多个控制器使用同一服务,它们将共享该状态。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM