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?


Solution 1:

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']);

Solution 2:

If you want to look for a good example, you should look into the current module written in angularJS. Learn to read their source code. Btw this is a structure that I use to write modules in angularJS:

var firstModule = angular.module('firstModule', [])
firstModule.directive();
firstModule.controller();

// in your app.js, include the module

This is the basic one.

Solution 3:

var newMod = angular.module('newMod', []);

newMod.controller('newCon', ['$scope', function ($scope) {
    alert("I am in newCon");
    $scope.gr = "Hello";
}]);

Here newMod is a module which has no dependencies [] and has a controller which has an alert telling you are in the controller and a variable with value hello.