简体   繁体   中英

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. 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. It uses angular.ng-modules.js .


EDIT: I'm trying to use Angular.js v.1.3.6. On version 1.2.x there is no problem with namespaces.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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