Angular.js namespacing modules controllers

359 Views Asked by At

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.

1

There are 1 best solutions below

1
On

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.