Home » JavaScript » Angular.js » AngularJS Dependency Injection Example

About Yatin

The author is graduated in Electronics & Telecommunication. During his studies, he has been involved with a significant number of projects ranging from programming and software engineering to telecommunications analysis. He works as a technical lead in the information technology sector where he is primarily involved with projects based on Java/J2EE technologies platform and novel UI technologies.

AngularJS Dependency Injection Example

Dependency Injection is a design pattern that divides the application into different components which can be injected into each other as dependencies. In this tutorial, we will understand how the dependency injection principle works in the angular library.

1. Introduction

Before we begin with the tutorial, let’s take a look and at the Angular JavaScript, Dependency Injection in angular and its characteristics.

1.1 Angular JavaScript

Angular is a JavaScript MVC or Model-View-Controller framework developed by Google that lets developers build well structured, easily testable, and maintainable front-end applications. But before we start creating a real application using the angular library, let us see what the important parts of an angular application are.

1.1.1 Templates

In Angular, a template is an HTML with added markups. The angular library compiles the templates and renders the resultant HTML page.

1.1.2 Directives

Directives are the markers (i.e. attributes) on a DOM element that tell angular to attach a specific behavior to that DOM element or even transform the DOM element and its children. Most of the directives in the angular library start with the ng. The directives consist of the following parts:

  • ng-app: The ng-app directive is a starting point. If the angular framework finds the ng-app directive anywhere in the HTML document, it bootstraps (i.e. initializes) itself and compiles the HTML template
  • ng-model: The ng-model directive binds an HTML element to a property on the $scope object. It also binds the values of angular application data to the HTML input controls
  • ng-bind: The ng-bind directive binds the angular application data to the HTML tags

1.1.3 Expressions

An expression is like a JavaScript code usually wrapped inside the double curly braces such as {{ expression }}. Angular library evaluates the expression and produces a result.

1.2 Dependency Injection in Angular

Dependency Injection is an important design pattern that implements the ‘inversion of control’ mechanism to resolve the dependencies of the components and thus making the code more maintainable, testable, and reusable. It provides the following components which can be injected into each other as dependencies.

1.2.1 Value based DI

In angular, a value is a simple javascript object that passes the value to the angular controller, factory or the service method during the run and the configuration phase. The value objects are defined using the value() function of the module and the angular functions can use these values by their names. This function has the following prototype form:

Value based DI

// Define a module
var app = angular.module("mainApp", []); 
// Create the value objects as the "defaultInput" & "objectValue" and pass it a data
app.value("defaultInput", 5);
app.value("objectValue", {  val1 : "hello", val2 : "world" } ); 

1.2.2 Factory based DI

In angular, a factory is a function that returns a value. When an angular service, controller etc. needs a value injected from a factory, the factory creates the value on demand. Once created, this value is reused for all the services, controllers etc. that need to be injected. The factory differs from the value as developers can inject values into a factory while creating an object but they cannot do that with a value. This function has the following prototype form:

Factory based DI

// Define a module
var app = angular.module("mainApp", []); 

// Create a factory method which display the greetings message
app.factory("myFactory", function() {  
    return "hello world";  

// Injecting the factory in a controller to use the output of the factory
app.controller("myCtrl", function($scope, myFactory) {  

1.2.3 Service based DI

In angular, a service is a function or a javascript object that do the specific tasks. The function contains a business logic for the service to carry out its work. For e.g. $http is a service in the angular library which when injected into the controller provides the implementation to the get(), query(), save(), remove, and the delete() methods. This function has the following prototype form:

Service based DI

// Define a module
var app = angular.module("mainApp", []); 

// Create a service which defines a method to return the square of a number.  
app.service('myService', function(multiple) {  
   this.square = function(a) {  
      return multiple.square(a, a);   

// Injecting the service (i.e. "myService") into the controller  
app.controller('myCtrl', function($scope, myService) {
   $scope.square = function() {
		$scope.result = myService.square($scope.number);

1.2.4 Provider based DI

In angular, a provider is a flexible form of the factory function which is internally used by the angular framework to create the service, factory etc. during the configuration phase. Developers register a provider with the angular module by using the provider() function. The provider object has a get() function which creates whatever the provider creates (i.e. service, value etc.). This function has the following prototype form:

Provider based DI

// Define a module
var app = angular.module("mainApp", []); 
// Create a service using the provider which defines a method to return the square of a number.  
app.config(function($provide) {  
   $provide.provider('myService', function() {  
      this.$get = function() {  
         var factory = {};    
         factory.multiply = function(a, a) {  
            return a * a;   
         return factory;  

1.2.5 Constant based DI

In angular, a constant passes the values at the configuration phase. These values are defined using the module.constants() function and cannot be injected into the module.config() function. This function has the following prototype form:

app.constant("configParam", "constant value");

1.3 Why Dependency Injection?

Dependency injection allows:

  • Separate creation and use of the dependencies
  • Easy change of the dependencies on a need basis
  • Allow easy reuse of the customs services across multiple angular modules
  • Allow dummy objects injection for testing
  • Offer loose coupling by removing the hard-coded dependencies

1.4 Familiar services in Angular

In a real world, developer’s first contact with the Dependency Injection principle is with the $scope value in the controller. The other common services are listed below:

$httpThis parameter allows access to the HTTP requests
$resourceThis parameter provides a higher-level abstraction for accessing the REST-style services
$documentThis parameter is a jQuery lite reference to the window.document function
$windowThis parameter is a jQuery lite reference to window
$timeoutThis parameter is a jQuery lite reference to the window.setTimeout function. Developers can use the $timeout.flush() function to synchronously execute all the scheduled timeouts
$parseThis parameter parses the angular expressions
$cacheFactoryDevelopers can use this parameter if the angular services need a scoped cache of elements
$filterThis parameter provides an access to a filter function

These new APIs make developer’s life easier, really! But it would be difficult for a beginner to understand this without an example. Therefore, let us create a simple example to show the dependency injection in the angular library.

2. AngularJS Dependency Injection Example

Here is a step-by-step guide for implementing the dependency injection in the angular web applications.

2.1 Tools Used

We are using Eclipse Kepler SR2, JDK 8 and Maven. Having said that, we have tested the code against JDK 1.7 and it works well.

2.2 Project Structure

Firstly, let’s review the final project structure if you are confused about where you should create the corresponding files or folder later!

Fig. 1: Application Project Structure

Fig. 1: Application Project Structure

2.3 Project Creation

This section will show how to create a Java-based Maven project with Eclipse. In Eclipse Ide, go to File -> New -> Maven Project.

Fig. 2: Create Maven Project

Fig. 2: Create Maven Project

In the New Maven Project window, it will ask you to select project location. By default, ‘Use default workspace location’ will be selected. Just click on next button to proceed.

Fig. 3: Project Details

Fig. 3: Project Details

Select the ‘Maven Web App’ Archetype from the list of options and click next.

Fig. 4: Archetype Selection

Fig. 4: Archetype Selection

It will ask you to ‘Enter the group and the artifact id for the project’. We will enter the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT.

Fig. 5: Archetype Parameters

Fig. 5: Archetype Parameters

Click on Finish and the creation of a maven project is completed. If you see, it has downloaded the maven dependencies and a pom.xml file will be created. It will have the following code:


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

3. Application Building

Let’s start building an application to understand the basic building blocks of the dependency injection principle in the angular library.

3.1 Load the Angular framework

Since it is a pure JavaScript framework, we should add its reference using the <script> tag.

<script type="text/javascript" src="resource/js/angular_v1.6.0.js"></script>

3.2 Define the Angular application

Next, we will define the angular application using the <ng-app> and <ng-controller> directives.


<div ng-app="myApp" ng-controller="CalCtrl">

3.3 Create the Angular controller

The calculator.js javascript file will process the data entered by the user. In this file, we are injecting the angular service within an angular controller and using the angular factory method to find the square of a number.


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

//============ (a) Injecting the service within an Angular controller =============//
app.controller('CalCtrl',function($scope, CalcService) {
	$scope.square = function() {
		$scope.result = CalcService.square($scope.number);

//============ (b) Injecting the service within a Angular service =============//
app.service('CalcService', function(multiple) {
	this.square = function(a) {
		return multiple.square(a, a);

//============ (c) Creating the Angular factory =============//
app.factory('multiple', function() {
	var factory = {};
	factory.square = function(a, b) {
		return a * b;
	return factory;

3.4 Complete Application

In this example, we have defined the <ng-model> directive to the HTML input control and we are using the same <ng-model> value for displaying the square of a number. Complete the above steps to show the front view and understand the use of dependency injection in an angular web application.


<!DOCTYPE html>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
      <title>AngularJS DI</title>
      <!-- AngularJs Files -->
      <script type="text/javascript" src="resource/js/angular_v1.6.0.js"></script>
      <script type="text/javascript" src="resource/js/calculator.js"></script>	
      <!-- Bootstrap File -->
      <link rel="stylesheet" href="https://www.webcodegeeks.com/wp-content/litespeed/localres/aHR0cHM6Ly9tYXhjZG4uYm9vdHN0cmFwY2RuLmNvbS8=bootstrap/4.0.0-alpha.6/css/bootstrap.min.css">          
      <div id="angularInjection" class="container">
         <h1 align="center" class="text-primary">AngularJS - Dependency Injection Example</h1>
         <hr />

         <div ng-app="myApp" ng-controller="CalCtrl">
         	<div class="form-group">
         		<label for="number" class="text-secondary">Enter a number</label>       
            	<input id="number" name="number" class="form-control" type="number" ng-model="number" placeholder="Enter a number" />

            <!------ SUBMIT BUTTON ------>
            <div id="getSqrBtn">
               <button id="sqrBtn" type="button" class="btn btn-primary" ng-click="square()">X<sup>2</sup></button>

            <div id="output">
            	<p id="pText" class="text-info">Result: <strong>{{ result }}</strong></p>

4. Run the Application

As we are ready for all the changes, let us compile the project and deploy the application on the tomcat server. To deploy the application on Tomat7, right-click on the project and navigate to Run as -> Run on Server.

Fig. 6: How to Deploy Application on Tomcat

Fig. 6: How to Deploy Application on Tomcat

Tomcat will deploy the application in its web-apps folder and shall start its execution to deploy the project so that we can go ahead and test it in the browser.

5. Project Demo

Open your favorite browser and hit the following URL. The output page will be displayed.


Server name (localhost) and port (8080) may vary as per your Tomcat configuration.

Fig. 7: Output page

Fig. 7: Output page

As the user puts a value in the input text-box and clicks the button, the square of a number will be displayed as shown below.

Fig. 8: Dependency Injection in an Angular application

Fig. 8: Dependency Injection in an Angular application

That’s all for this post. Happy Learning!!

6. Conclusion

In this section, developers learned about the concept and several benefits of using the dependency injection in the angular library. Some of these benefits are:

  • Reduced dependencies
  • More Reusable and Testable code
  • More Maintainable and Readable code
  • Dummy services for testing

Developers can download the sample application as an Eclipse project in the Downloads section.

7. Download the Eclipse Project

This was a tutorial of dependency injection in the angular library.

You can download the full source code of this example here: AngularDependencyInjectionEx

Do you want to know how to develop your skillset to become a Web Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!


1. Building web apps with Node.js

2. HTML5 Programming Cookbook

3. CSS Programming Cookbook

4. AngularJS Programming Cookbook

5. jQuery Programming Cookbook

6. Bootstrap Programming Cookbook


and many more ....


I have read and agree to the terms & conditions


Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments