San Jay Falcon San Jay Falcon - 11 days ago 6x
AngularJS Question

How do I write a custom module for AngularJS?

I need to write a custom module for AngularJS, but I can't find any good documentation on the subject. How do I write a custom module for AngularJS that I can share with others?


In these situations were you think that the docs can't help you any more, a very good way to learn is to look at other already-build modules and see how others did it, how they designed the architecture and how they integrated them in their app.
After looking at what others did, you should have at least a starting point.

For example, take a look at any angular ui module and you will see many custom modules.
Some define just a single directive, while others define more stuff.

Like @nXqd said, the basic way to create a module is:

// 1. define the module and the other module dependencies (if any)
angular.module('myModuleName', ['dependency1', 'dependency2'])

// 2. set a constant
    .constant('MODULE_VERSION', '0.0.3')

// 3. maybe set some defaults
    .value('defaults', {
        foo: 'bar'

// 4. define a module component
    .factory('factoryName', function() {/* stuff here */})

// 5. define another module component
    .directive('directiveName', function() {/* stuff here */})
;// and so on

After defining your module, it's very easy to add components to it (without having to store your module in a variable) :

// add a new component to your module 
angular.module('myModuleName').controller('controllerName', function() {
    /* more stuff here */

And the integration part is fairly simple: just add it as a dependency on your app module (here's how angular ui does it).

angular.module('myApp', ['myModuleName']);