AngularJS > Components

Modules in AngularJS

What are modules in AngularJS?


Module is a container for different parts of AngularJS application like controllers, filters, services etc.

  • This is the place where we write code for Angular application 
  • It makes our code more maintainable, testable and easily readable
  • This is also a place to define dependencies in our app

Why Module?

Most applications have a main method that gets instantiated when the appliation runs for the first time and this method instantiate different parts of the application.

AngularJS doesn't have main method, so it uses module that specifies how an application should be started. The benefits of this approach are following

  • We can create a reusable modules
  • Modules can be loaded in any order
  • Unit test doesn't need to load all the app, just loading that specific module is enough to start unit testing
  • Its easy to understand

How to define a module?

To create a module, we use angular.module method. It accepts two parameters

  1. 1st parameter - the name of the module
  2. 2nd parameter - the array of module names on which this module is dependent on

angular.module('app', []);
// OR
var app = angular.module('app', []); 

In above code snippet, we have defined a module named "app", as the second parameter is blank array so we are instructing AngularJS that this module is not dependent on any another module.

app = angular.module('app', ['app.ui', 'app.chart']);
// OR
var app = angular.module('app', ['app.ui', 'app.chart']);

In above code snippet, we have instructed AngularJS that "app" module is depdendent on "app.ui" and "app.chart" module.

 Views: 14706 | Post Order: 7




Write for us






Hosting Recommendations