AngularJS - Why & How to Create Custom Module
AngularJS - Why & How to Create Custom Module
Join the DZone community and get the full member experience.
Join For FreeAccess over 20 APIs and mobile SDKs, up to 250k transactions free with no credit card required
- Why create a custom module?
- How to create a custom module?
Why Create A Custom Module?
A module in AngularJS wires together some of the following components:
- Controllers
- Directives
- Filters
- Service
- A module per feature could be designed.
- It would be good to group similar/related service, filters and directives as part of the module for future reuse.
How to Create A Custom Module?
Creating a custom module is as simple as using angular.module API thereby passing the name and module dependencies and, defining one or more components. Take a look at following:
angular.module( "ModuleName", [] ) .factory( "ServiceName", [ 'depName', function( depName){ // code goes here... }]) .filter( "filterName", [ 'depName', function(depName)]{ // code goes here... }) .directive( "directiveName", [ 'depName', function( depName ){ // code goes here... }])
At lower level, a module is primarily a collection of two kind of blocks that are following:
- Configuration blocks: Configuration blocks get executed during the provider registrations and configuration phase. Only providers and constants can be injected into configuration blocks. The above code, actually, is applied as configuration blocks in that order in the following way:
angular.module('ModuleName', []). config(function($provide, $compileProvider, $filterProvider) { $provide.factory('ServiceName', [ 'depName', function( depName){ // code goes here... }]); $filterProvider.register('filterName', [ 'depName', function(depName)]{ // code goes here... }]); $compileProvider.directive('directiveName', [ 'depName', function( depName ){ // code goes here... }]) });
- Run blocks: Run blocks get executed after the injector is created and are used to kickstart the application. Only instances and constants can be injected into run blocks.
#1 for location developers in quality, price and choice, switch to HERE.
Published at DZone with permission of Ajitesh Kumar , DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}
{{ parent.urlSource.name }}