When working on large projects in AngularJS, I found that I like organizing code by functionality.
That means that when I have some recognizable functionality X (especially if it is reusable) I create directory X and put into it all controllers, services and other parts that belong to that functionality. I also declare a new module called X and assign everything in directory X to that module.
Directory structure would then look something like this:
scripts/
app.js
controllers/
services/
directives/
filters/
X/
controllers/
services/
directives/
filters/
In app.js there is a main module declaration:
angular.module('myApp', ['X']);
All controllers etc. in X/ belong to module 'X', which means I fetch module 'X' like this in those files:
var X = angular.module('X');
What I am not sure how to do is where to declare module 'X'?
Some ideas I had:
- I could declare it in one of the controllers/services/... and fetch it in other controllers etc. but that does not sound right because I do not see any logic how to pick that controller/service/... among others, and also then I have to take care to include it in index.html before others. I find this idea bad.
- I can put declaration in app.js, so app.js would now look like
angular.module('myApp', ['X']); angular.module('X', [/*some dependencies could go here*/]);
I find this idea better than the previous one, however I do not like that module declaration is outside of directory X. - In directory X/ I create file main.js and put declaration of module X in it. I have to be careful to include this file in index.html before other files from directory X/.
I like this solution the best.
Is there any better way to do this?