KodeBLOG

Kode Blog - Inspiring And Empowering Developers.

Home About Us Courses Categories Blog Contact Us

AngularJS Module

Introduction

Modular programming isnít unique to AngularJS. Modular programming allows us to break down a large application into modules (smaller manageable parts). AngularJS supports the concept of modular programming. A module in AngularJS allows us to create containers for our code.

This tutorial introduces you to working with modules in AngularJS and values, constants, factories and services.

Topics to be covered

We will cover the following topics in this tutorial

  • Tutorial Pre-requisites
  • Advantages of modules
  • AngularJS module example
  • AngularJS module controller
  • AngularJS Value
  • AngularJS Constant
  • AngularJS Factory
  • AngularJS Service
  • AngularJS module dependencies

Tutorial Pre-requisites

This tutorial assumes you have;

  • Basic knowledge of AngularJS
  • A web server i.e. Apache
  • Bower
  • Text editor or IDE
  • Modern Web browser
  • Hot cup of coffee [Optional]

Advantages of modules

Modules have the following advantages;

  1. Avoid code collisions Ė modules allow us to keep our variables, functions etc. into a container. This means the variables and functions wonít be accessible in the global (window) namespace
  2. Modules can be packaged and reused in other applications
  3. Modules can it easy to write unit tests

AngularJS module example

Letís now get our hands dirty. We will start by creating a simple tutorial project. For this tutorial, I am using a windows and machine and I have XAMPP that comes with apache as the web server.

I will start by creating a new project in the web root angular-modules

Open the command prompt / terminal and browser to the project root. Assuming you are using windows and have XAMPP installed on drive C, run the following command

cd C:\xampp\htdocs\angularjs-modules

Run the following command to install AngularJS using bower

bower install angularjs
bower install angular-route

Letís now create three directories app, js and controllers

Open the command prompt / terminal.

Run the following command to create the app directory. All of our AngularJS scripts will be in this directory.

mkdir app
cd app
mkdir controllers

AngularJS Module syntax

Letís now define a module for our application

Create a new file app.js in app directory

Add the following code to app/app.js

var myApp = angular.module("myApp", []);

HERE,

  • var myAPP defines a JavaScript variable
  • angular.module("myApp", []); defines a module. myApp is the name of the module. [] is used to inject module dependencies. In our example, we are not injecting any dependencies yet.

AngularJS module controller

We will now define a controller for our module. We will define the controller in a separate file. This is considered a best practice when developing AngularJS applications.

Create a new file homeController.js in app/controllers directory

Add the following code to app/controllers/homeController.js

myApp.controller('HelloController', hello);

function hello($scope)
{

}

HERE,

  • myApp.controller('HelloController', hello); myApp is the variable that we defined in app.js. It is available in homeController.js because myApp is in the global namespace
  • HelloController is the name of the controller and hello is the name of the function that is executed when HelloController is called.
  • function hello($scope){} is the function that the controller HelloController executes

Letís now define the HTML for our application

Create a new file index.html in the root directory

Add the following code to index.html

<!DOCTYPE html>
<html ng-app="myApp">
    <head>
        <title>AngularJS  Tutorial Series</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width">
    </head>
    <body>
        <div  ng-controller="HelloController">Welcome to AngularJS Modules Tutorial</div>

        <!óAngular JS Scripts -->
        <script src="bower_components/angularjs/angular.min.js"></script>
        <script src="bower_components/angular-route/angular-route.min.js"></script>

        <!-- AngularJS Application Specific Scripts -->
        <script src="app/app.js"></script>
        <script src="app/controllers/homeController.js"></script>
    </body>
</html>

HERE,

  • <html ng-app="MyApp"> the directive ng-app binds the HTML code to our module MyApp

AngularJS Value

AngularJS values are used to create global variables within the module without being available in the global namespace. Values can be strings, numbers or objects.

Values are used to store information such as currently logged in user etc.

We will add three values to our module, a string, number and object

Open app.js

Add the following lines just below the module declaration

myApp.value("piValue", 3.14159);

myApp.value("ourPlanet", "Earth");

myApp.value("user", { id : 13, name : "Rodrick Kazembe", email : "rodrickkazembe@example.com"} );

HERE,

  • myApp.value("piValue", 3.14159); defines the value piValue with a numeric value of 3.14159
  • myApp.value("ourPlanet", "Earth"); defines the value ourPlanet with a string value of Earth
  • myApp.value("user", { id : 13, name : "Rodrick Kazembe", email : "rodrickkazembe@example.com"} ); defines a value user of object type.

AngularJS injecting values into controllers

Letís now update the home controller

Update the code to the following

myApp.controller('HelloController', hello);

function hello($scope,piValue,ourPlanet,user)
{
    $scope.piValue = piValue;
    $scope.ourPlanet = ourPlanet;
    $scope.user = user;
}

HERE,

  • function hello($scope,piValue,ourPlanet,user) injects the values piValue, ourPlanet,user
  • $scope.valueName = valueName; assigns the values to the respective value names

Letís now update index.html to see the effects

Update the controller div to the following code

<div  ng-controller="HelloController">
    Welcome to AngularJS Modules Tutorial
    <h4>Values examples</h4>
    <p>The value of pi is: {{piValue}}</p>
    <p>Our planet is: {{ourPlanet}}</p>
    <p>Logged in user details</p>
    <ul>
        <li>id : {{user.id}}</li>
        <li>name : {{user.name}}</li>
        <li>email : {{user.email}}</li>
    </ul>
</div>

HERE,

  • The above code gets the values assigns to $scope and displays them in the browser.

Open the following URL in your web browser

http://localhost/angular-modules/

You will get the following results

AngularJS Values

AngularJS Constant

Constants are similar to values expect they are read only values. You can change the value of a value during the life cycle of an application. With a constant, you can only retrieve its value. You cannot change it.

Constants are very useful for defining things like the application name, version, API URLs etc.

Letís now define the application name, version and API URL

Open /app/app.js

Itís kind of customary to use capital letters when defining constants. We will do that in this section. Add the following lines

myApp.constant("APP_NAME", "AngularJS Invoicing App");

myApp.constant("APP_VERSION", "1.3");

myApp.constant("API_URL", "http://localhost/malipo-api/v1/");

HERE,

  • myApp.constant("APP_NAME", "AngularJS Invoicing App"); defines a constant APP_NAME in the module myApp. At the end of these tutorial series, we will create a complete invoicing application in AngularJS. Subscribe to get updates delivered to your mail box.
  • myApp.constant("APP_VERSION", "1.3"); defines the application version number
  • myApp.constant("API_URL", "http://localhost/malipo-api/v1/"); defines the base API URL for the backend.

We will now set the page title of our AngularJS application dynamically

Just like values, we will need to inject the constants to our controller so that we can use the values.

Open /app/controllers/homeController.js

Modify hello function to the following code

function hello($scope,piValue,ourPlanet,user,APP_NAME,APP_VERSION,API_URL)
{
    $scope.piValue = piValue;
    $scope.ourPlanet = ourPlanet;
    $scope.user = user;

    $scope.title = APP_NAME + " Version " + APP_VERSION;
}

HERE,

  • APP_NAME,APP_VERSION,API_URL injects the constants to the controller function
  • $scope.title = APP_NAME + " Version " + APP_VERSION; concatenates the constants to create the application title and assigns the result to a variable title

Letís now update index.html

We bonded our controller to the div element. We will now expand the scope and bind it to the HTML tag so that information from the controller will be available to all the pages.

Update the following div

<div ng-controller="HelloController">

to

<div>

Update

<html ng-app="myApp">

to

<html ng-app="myApp" ng-controller="HelloController">

This will make the data from our controller available to the entire elements in the HTML documents

Update the title tag to the following

<title>{{title}}</title>

HERE,

ē {{titile}} displays the value of the variable title that we set in the hello function for the controller HomeController

AngularJS Factory

Factories are similar to values. The similarity is they all return values. The difference is a factory uses a function to create the value on demand while a value doesnít.

When should you use a factory in AngularJS

Because factories use functions, you can use them to encapsulate complex business logic and return the result without exposing the complexity to the component that is using the factory.

AngularJS factory example

The following is the syntax for declaring factories

moduleName.factory('factoryName', function(){return value});

HERE,

  • moduleName is the reference to the module that will contain the factory
  • .factory('factoryName', function){Ö}; is used to create a factory named factoryName

Letís now look at how we can add a factory to our simple AngularJS application. For the sake of simplicity, we will work with a very basic example.

Open /app/app.js

Add the following line

myApp.factory("helloFactory", function() {
    return "I greet in peace from the factory";
});

HERE,

  • myApp makes reference to the module where we want to create the factory
  • helloFactory,function{Ö} is the name of the factory that returns a simple message I greet in peace from the factory

Open /app/controllers/homeController.js

We will need to inject the factory into the controller

Update the function hello to the following

function hello($scope,piValue,ourPlanet,user,APP_NAME,APP_VERSION,API_URL,helloFactory)
{
    $scope.piValue = piValue;
    $scope.ourPlanet = ourPlanet;
    $scope.user = user;

    $scope.title = APP_NAME + " Version " + APP_VERSION;

    $scope.helloFactory = helloFactory;
}

HERE,

  • $scope.helloFactory = helloFactory; assigns the value of helloFactory to a variable helloFactory in $scope

Letís now update index.html so that we can display the value from the factory

Add the following lines to our div with other values

<h4>Factory examples</h4>
<p>helloFactory returned: {{helloFactory}}</p>

Load the following URL in your browser

http://localhost/angular-modules/

You will get the following message in your browser

Factory examples
helloFactory returned: I greet in peach from the factory

Letís now take things a notch up. Factories are used mainly for complex business logic and as such, you may need to pass parameters to a factory.

AngularJS Factory parameter

Suppose you are developing an invoicing application and you want to use a factory to compute the VAT. The factory should accept a parameter with the amount and compute the VAT based on the amount.

Open /app/app.js and add the following line

myApp.factory("VAT", function() {
    return {
        compute: function(total_amount){
            return total_amount * 0.18;
        }  
    } 
});

HERE,

  • compute: function(total_amount){Ö} is a function defined within the factory that accepts a parameter total_amount. The definition of the factory itself does not take any parameters

Letís now modify /app/controllers/homeController.js and inject the factory VAT.

function hello($scope,piValue,ourPlanet,user,APP_NAME,APP_VERSION,API_URL,helloFactory,VAT)
{
    $scope.piValue = piValue;
    $scope.ourPlanet = ourPlanet;
    $scope.user = user;

    $scope.title = APP_NAME + " Version " + APP_VERSION;

    $scope.helloFactory = helloFactory;

    $scope.vat = VAT.compute(100);
}

HERE,

  • $scope.vat = VAT.compute(100); calls compute method of the function VAT and passes in a parameter of 100 as the total amount.

Add the following to index.html to display the vat value

<p>The VAT amount is ${{vat}}</p>

Load the following URL in your web browser

http://localhost/angular-modules/

You will get the following result

The VAT amount is $18

AngularJS Service

The difference between a factory and a service is a thin blue line. Based on the research that we carried out, the major difference is a service can be instantiated while a factory cannot be instantiated. Most developers seem to use factories. If you are not sure about what to use between a factory and a service, common wisdom dictates you use a factory.

AngularJS Service Example

The following is the syntax for creating services in AngularJS

moduleName.service('serviceName', function(){return value});

HERE,

  • moduleName is the reference to the module that will contain the service
  • .service('servuceName', function){Ö}; is used to create a service named serviceName

Letís now define a service that displays a simple greeting

Open /app/app.js

Add the following code

myApp.service('helloService', function(){
    this.bite= function(){
        return "Hey watch it! I bite";
    };        
});

HERE, ē myApp.service('helloService', function(){Ö} defines a services helloService ē this.bite= function(){Ö} defines a function within the service that displays a message

Modify the controller function in homeController.js to the following code

function hello($scope,piValue,ourPlanet,user,APP_NAME,APP_VERSION,API_URL,helloFactory,VAT,helloService)
{
    $scope.piValue = piValue;
    $scope.ourPlanet = ourPlanet;
    $scope.user = user;

    $scope.title = APP_NAME + " Version " + APP_VERSION;

    $scope.helloFactory = helloFactory;

    $scope.vat = VAT.compute(100);

    $scope.helloService = helloService.bite();
}

Add the following code to index.html

<h4>Service examples</h4>
<p>helloService returned: {{helloService}}</p>

Load the following URL in your browser

http://localhost/angular-modules/

You will get the following results

helloService returned: Hey watch it! I bite

AngularJS Service Parameter

Letís now add create another service that accepts a parameter. For the sake of simplicity, you will add a simple hello + name example.

Modify helloService function in app.js to the following code

myApp.service('helloService', function(){
    this.bite= function(){
        return "Hey watch it! I bite";
    };  

    this.hello= function(name){
        return "Hello " + name;
    };        
});

Open homeController.js and add the following line

$scope.helloServiceName = helloService.hello("Rodrick");

HERE,

  • helloService.hello("Rodrick"); call hello function in helloService and passes Rodrick as a parameter

Add the following line to index.html

<p>helloServiceName returned: {{helloServiceName}}</p>

If you view the application in the browser, you will get the following message

helloServiceName returned: Hello Rodrick

AngularJS module dependencies

Throughout this tutorial, we have been working with a single module. On large applications, it is considered a best practice to define several modules and inject other modules that a specific module will need to use.

Open /app/app.js

Modify the first line to the following

var myApp = angular.module("myApp", ['ngRoute','myApp.Controllers']);

HERE,

  • We injected myApp.Controllers as a module dependency. Notice the name is myApp.Controller. This makes it easier to tell that myApp is the top level module and other modules are inside it. This is considered a best practice.

Letís now modify homeController.js to the following

var myAppControllers = angular.module("myApp.Controllers", []);

myAppControllers.controller('HelloController', hello);

function hello($scope,piValue,ourPlanet,user,APP_NAME,APP_VERSION,API_URL,helloFactory,VAT,helloService)
{
    $scope.piValue = piValue;
    $scope.ourPlanet = ourPlanet;
    $scope.user = user;

    $scope.title = APP_NAME + " Version " + APP_VERSION;

    $scope.helloFactory = helloFactory;

    $scope.vat = VAT.compute(100);

    $scope.helloService = helloService.bite();

    $scope.helloServiceName = helloService.hello("Rodrick");
}

HERE,

  • var myAppControllers = angular.module("myApp.Controllers", []); defines a module myApp.Controllers and assigns the object to a variable myAppControllers
  • myAppControllers.controller('HelloController', hello); attaches the controller to the object variable myAppControllers
  • The rest of the code remains the same.

Load the following URL in your web browser

http://localhost/angular-modules/

You will get the following results

AngularJS Modules

Summary

Modularizing an AngularJS application makes it easy to share code between applications, write unit tests and avoid code collisions among other things. Values and constants are useful for creating global variables within modules without polluting the global namespace. Factories and services are idea for business logic.

Whatís next?

The best way to learn is by practice. The next tutorial will layout the foundation for an invoicing application in AngularJS. Each new tutorial will teach you core concepts of AngularJS and add value to the invoicing application.

If you found this tutorial useful, support us by using the social media buttons to like and share the tutorial. If you didnít find it useful, please use the comments section below to let us know how we can do better next time.

Each week, a new AngularJS tutorial is added to our collection. Subscribe to our newsletter, like our Facebook fan page or follow us on Twitter to get free updates when the collection is updated.

Tutorial History

Tutorial version 1: Date Published 2015-10-22