AngularJS And Module Pattern

In the AngularJS world, EVERYTHING is a module. AngularJS modules can be defined in any order, including dependency modules that haven’t been defined yet, and still work properly. The only prerequisite is that the Angular.js core is loaded first.

The Module pattern in JavaScript, in it's most basic form, is a self-executing function that:

Provides variable scope encapsulation
Imports any dependencies trough function parameters
Exports its own functionality as a return statement

var MyModule = ( function( dependency ) { var myScopedVar = dependency || {}; return { //module logic }; })(dependency);

This is how my first code looked like, you will also see this kind of approach in a lot of samples.

//app.js var application = angular.module('MyApp',[]);

//controller.js (function(app) { 'use strict'; app.controller("YourController", function($scope) {/* … */ }]); })(application);

As you can see, I’m creating a module and saving it into a variable. Followed by a self-invoking anonymous function expression. Then using an application variable to extend it 'and yes this works', but actually it’s a bit wrong as it pollutes the global namespace.

You could therefore simply use the chained syntax like this:

//app.js (function() { 'use strict'; angular.module('MyApp', []) .controller("YourController", function() { /* ... */ }) .directive("YourDirective", function() { /* ... */ }) })();

The drawback of this approach is, that it appears like you'd have to define all parts of your module in one source file. This isn't what you'd like to do in any application. But there is more, AngularJS is providing you a way to re-open a module like so:

// Notice: the only difference is the presence or absence of an array as the 2nd argument. angular.module('MyApp');

With this in mind we can now define our code like this:

//app.js (function() { 'use strict';
angular.module('MyApp', ['', 'MyApp.controllers', 'MyApp.directives']);
angular.module('MyApp.directives', []); angular.module('MyApp.controllers', []); angular.module('', []); })();

//Directives.js (function() { 'use strict';
angular.module('MyApp.directives') .directive(' YourDirective', function() { /* ... */ }); })();

//Controllers.js (function() { 'use strict';
angular.module('MyApp.controllers') .controller(' YourController', function() { /* ... */ }); })();

//Services.js (function() { 'use strict';
angular.module('MyApp.controllers') .factory (' YourService', function() { /* ... */ }); })();

Just keep in mind that you only have to specify the dependency-array on the first call to module, as you would otherwise redefine the module's dependency list. This instead of adding additional parts to an existing module.