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:
angular.module('myApp', ['X']);
angular.module('X', [/*some dependencies could go here*/]);
Is there any better way to do this?
Yes, you can define multiple modules in angularJS as given below. The modularization in AngularJS helps us to keep the code clarity and easy to understand, as we can combine multiple modules to generate the application.
Injecting a value into an AngularJS controller function is done simply by adding a parameter with the same name as the value (the first parameter passed to the value() function when the value is defined). Here is an example: var myModule = angular. module("myModule", []); myModule.
Yes. Third option is the best solution. First option will definitely give a pain in the neck. Second option adds a dependency of module X in the main app, which is not desirable. You would want your module to be self-contained. So third option is the best solution.
Here is the best practice recommendations from Google which you are actually trying to adhere to. :) Moreover, it will also be great for you (as suggested by Google's best practice) to not separate the files by artifacts, which means you do not need controllers, directives, etc dir structure as below. Also note partials, CSS and even tests are in the component are contained in the component/module directory. Hence the module is totally contained and independent, which helps in reusability:
sampleapp/
app.css
app.js
app-controller.js
app-controller_test.js
components/
bar/ "bar" describes what the service does
bar.js
bar-service.js
bar-service_test.js
bar-partial.html
foo/ "foo" describes what the directive does
foo.js
foo-directive.js
foo-directive_test.js
foo-partial.html
index.html
I hope this will be helpful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With