My current twitter avatar

zaccary price

Front-end developer and designer, currently based in Helsinki, Finland

Create a better AngularJS application structure using modules

21 Apr 2014

AngularJS' extensibility is not inherent in it's design, rather it's a feature that must be exploited to ensure efficient development and ease of comprehension. The first move should be to not have any functionality that, at the least, isn't required to be used during the app's initialization. While this is useful from an organizational perspective, it will make things messy when having to refer to the app's root module all the time. What you can do instead is create modules for all the different aspects of Angular. Creating a module for your services, controllers, directives and so forth will not only allow for better organization of your project, but also optimise the use of plugins in the future.

These modules should be initialized in your app.js (or the root script file for the project) as such:

angular
    .module('<app-name>.<component>', []);
    // as many modules as you need with the same format

Where 'app name' is the root module name, say 'App', and the component is your services, controllers and so forth. Using this example, your controllers module would be initialized thusly:

angular
    .module('App.Controllers', []);

This module naming convention doesn't follow any standard enforced by angular itself, rather it's just an easy to comprehend format. Also note the empty array after the name, this is for injecting any third party modules you may wish to use. It's required for initialization so either leave it empty or add something there if you have something.

Using the modules, now initialized in your app root, is done by referencing them. Creating a new controller would be therefor done as such:

angular
    .module('App.Controllers')
    .controller('FooCtrl', ['$scope', function($scope) {
    /* controller stuff */
}]);