How to write a custom module for AngularJS?

I need to write my own module for AngularJS, but I can not find good documentation on this. How to write a custom module for AngularJS that I can provide to other users?

+44
angularjs
Oct 01 '13 at 6:18
source share
3 answers

In these situations, you thought that the documents would no longer help you, a very good way to learn is to look at the other modules of the finished assembly and see how others did it, how they designed the architecture and how they integrated them into their application.
Looking at what others have done, you should have at least a starting point.

For example, look at any angular ui module , and you will see many custom modules.
Some define only one directive , while others define more things .

Like @nXqd , the main 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 is 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 pretty simple: just add it as a dependency on your application module ( here , how angular ui does it).

 angular.module('myApp', ['myModuleName']); 
+80
01 Oct '13 at 6:57 on
source share

If you want to find a good example, you should study the current module written in angularJS. Learn to read their source code. Btw is the 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 main one.

+5
01 Oct '13 at 6:28
source share
 var newMod = angular.module('newMod', []); newMod.controller('newCon', ['$scope', function ($scope) { alert("I am in newCon"); $scope.gr = "Hello"; }]); 

Here, newMod is a module that has no dependencies [] and has a controller that has a warning indicating that you are in the controller and a variable with the value hello.

+2
Oct 17 '14 at 3:36 on
source share



All Articles