AngularJS Module Tutorial Example

In this post, we are going to cover one of the most important feature in AngularJS called Modules. We looked at features like controllers, filters and directives in the previous posts. We have also discussed how to create and include controllers in angular application, but it is not a recommended way to do, especially when you are dealing with big applications. We can use AngularJS Module API to modularize angular applications.


What is a Module?

Module can be treated as a container for the different parts of your application like controllers, filters, services, directives ,etc, which specify how an application should be bootstrapped. Module is an important part of the AngularJS dependency injection system.

Here is the general syntax for creating a module:

  • angular.module(“myModule”, []);

Here myModule is the name of the module. [] is where you inject the dependencies.

Why Modules?

  • Helps package our code into reusable modules.
  • The declarative process is easier to understand.
  • Modules can be loaded in any order.
  • Easily testable and maintainable components.
  • Helps organize your application.

Creating a Controller in a Module

In this section, we are going to explain how to create a controller in a module. It is very simple and we use the following steps to achieve that task.

Here we have created a module called myFirstModule and defined a controller named MyController in it.

You can also create services, providers and factories using the angular module API. The following table briefly describes some of the mostly used methods in the API.

Method Syntax
module.service module.service( ‘serviceName’, function );
module.factory module.factory( ‘factoryName’, function );
module.provider module.provider( ‘providerName’, function );

In this post, we are not going to look into the details of these concepts. We will see these concepts in the coming posts.

Creating a Controller in a Module Example

The following example demonstrates how to create a controller in angular module. In this example, we will create a module called demoApp and will define the controller, blogController in it.


We use ng-app directive to specify the name of the module used in the application. You will see the following output in your browser.

AngularJS Application Files

Earlier we looked at how to include controllers in external files. That is very helpful when you deal with big applications. In any angular application, we use mainly two types of files, one with module and other with controllers. Let’s look in to it.
The following example demonstrates this usage.

First, we create a module in the app.js file.


Second step is to define the controllers in controller.js file.


Third step is to include these two files in our application.


You will see the following output in your browser.

That’s all for now and we will see more angular concepts in the coming posts.

By admin

Leave a Reply