Working with Modules in Angular.js

What are Modules in Angular.js ?
We can think of a module as a container for the different parts of our app – controllers, services, filters, directives, etc. Angular JS supports modules, using which we can divide the JavaScript code involved in our application. Creating modules not only helps separating the code into individual concerns but also improves unit-testability. The modules can be easily replaced by some mocks while unit testing Angular controllers.Every module should have a name, which is specified in the first parameter. Second parameter to module function is an array, which may contain names of other modules or services. If the module doesn’t depend on anything, the array can be left blank. Let us look through a diagram for better understanding.


Why should we use modules?
To a module, we can add services, filters, directives, constants, configuration blocks and run blocks. In large applications, it is recommended to add each of these to separate modules.
Angular apps don’t have a main method. Instead modules declare specifically how an application should be bootstrapped. There are several advantages to this approach:

1)The declarative process is easier to understand.
2)You can package code as reusable modules.
3)The modules can be loaded in any order (or even in parallel) because modules delay execution.
4)Unit tests only have to load relevant modules, which keeps them fast.
5)End-to-end tests can use modules to override configuration.

Basic example of a module:
Let us see through a basic implementation of a module in ajs file.

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

Now we know how to create a module. So, using this method let us walk through a set of codes which will display the system time and date in a certain format. The user can define this format.

<!DOCTYPE html>
<html ng-app="myApp">

    <script data-require="angular.js@*" data-semver="1.3.0-beta.5" src=""></script>
    <script>angular.module('myApp', [])
    // register the controller for the app
    .controller('myController',['$scope', function($scope){
        $scope.format = 'M/d/yy h:mm:ss a';
    // Register the 'myCurrentTime' directive factory method.
        .directive('myCurrentTime', function($timeout, dateFilter) {
        // return the directive link function. (compile function not needed)
        return function(scope, element, attrs) {
            var format,  // date format
                timeoutId; // timeoutId, so that we can cancel the time updates

            // used to update the UI
            function updateTime() {
                element.text(dateFilter(new Date(), format));

            // watch the expression, and update the UI on change.
            scope.$watch(attrs.myCurrentTime, function(value) {
                format = value;

            // schedule update in one second
            function updateLater() {
                // save the timeoutId for canceling
                timeoutId = $timeout(function() {
                    updateTime(); // update DOM
                    updateLater(); // schedule another update
                }, 1000);

            // listen on DOM destroy (removal) event, and cancel the next UI update
            // to prevent updating time after the DOM element was removed.
            element.bind('$destroy', function() {

            updateLater(); // kick off the UI update process.
    <div ng-controller="myController">
      <h3>Basic  Angularjs Module</h3>
      <p>Date = d , Month = M , Year = yy</p>
      <p>Hour = h , Minute = mm , Second = ss , AM/PM = a</p>
      <input type="text" ng-model="format" />
      <div>Current time is: <span my-current-time="format"></span>

In the above set of codes as we can see , we are showing system time and date in a user specific format. To do that we have taken a text-box where user specifies the desired format. After giving the desired format the system time and date is shown.
In the java script file we have created a module named ‘myApp’ with an empty array. After that we have registered a controller. We have given the name ‘myController’. This controller will be called through ng-controller.

.controller('myController',['$scope', function($scope){

After registering the controller we will be in need of a directive to register. So that we can inject services like ‘$timeout’ and ‘datepicker’ .

 .directive('myCurrentTime', function($timeout, dateFilter) {

At the very last we also need to bind the information using ‘bind()’.

element.bind('$destroy', function() {

Module Loading & Dependencies:

A module is a collection of configuration and run blocks which get applied to the application during the bootstrap process. Modules can list other modules as their dependencies. Depending on a module implies that required module needs to be loaded before the requiring module is loaded. In other words the configuration blocks of the required modules execute before the configuration blocks of the requiring module. The same is true for the run blocks. Each module can only be loaded once, even if multiple other modules require it.

Configuration blocks – Get executed during the provider registrations and configuration phase. Only providers and constants can be injected into configuration blocks. This is to prevent accidental instantiation of services before they have been fully configured.

Run blocks – Get executed after the injector is created and are used to kick start the application. Only instances and constants can be injected into run blocks. This is to prevent further system configuration during application run time.

Creating a controller in a module:

    var app = angular.module('my-app', [], function() {
         app.controller('AppController', function($scope) {
      $scope.message = "Welcome controller";

The above code is an example of a simple controller in the module. So, let’s break up the code and try to understand completely.

As we can see in the beginning we are creating a module named my-app.

var app = angular.module('my-app', [], function() {

Now it is time to create the controller which will execute what we will tell it to. To create controller we will be using

 app.controller('AppController', function($scope) {

In the above line of code we are registering the controller with a name ‘AppController’. With that we are also using a scope as a function. After we provide the contents in the scope we just have to include the controller in html using ‘ng-controller’. After that to get the result we have to call the scope which we have used in the controller.

Creation and Retrival:

There is a major difference in between these two in case of modules. Using angular.module(‘myModule’, []) will create the module myModule and overwrite any existing module named myModule. Use angular.module(‘myModule’) to retrieve an existing module. Let us see some examples.

If we use this method there will be another module created and we won’t be able to get the desired result.

var app = angular.module('my-app', [], function() {
         app.controller('AppController', function($scope) {
      $scope.message = "Welcome controller";
var app = angular.module('my-app',[])

But if we use alter the above process with this. The same module will be retrived and we will get our desired result.

var app = angular.module('my-app', [], function() {
         app.controller('AppController', function($scope) {
      $scope.message = "Welcome controller";
var app = angular.module('my-app')

Related Links:
1>Directive in Angular.js – Part 1
2>Directive in Angular.js – Part 2
3>Angular Router and UI-Router
4>Angularjs and Services
5>Angular.js Promise
6>Angular.js Two Way Data Binding
7>How To Use Filter In Angular.js
8>Angular Templates
9>Using Controllers in Angular.Js
10>Angularjs with Server Side Interaction
11>Working Through Angular.js With Transclude
12>Angular.js Event Handling

If you find this article helpful, you can connect us in Google+ and Twitter.

17 thoughts on “Working with Modules in Angular.js

Leave a Reply

Your email address will not be published. Required fields are marked *