Dependency Injection is the pattern of designing software in which one or more services (known as dependencies) can be injected in the component (dependent object).

It makes our code more maintainable, testable and usable.

There are many components in which dependency can be applied like controllers, directives, filter,  service, factoryprovider, value, constant. But some of them are

But, some of them are non-injectable. It means you can’t inject them into a component such as controllers, directives, filter.

Rest of them are injectable and they are also called service creators.


Watch the live demo or download code from the link given below.


when any service is injected into a component. Injector called some method which creates the instance of that service then injector pass this instance of service to the component

dependency injection working diagram


Module Dependency:

Angular allows to inject a module within a module while creating it.

For Example:

 angular.module('myApp',['othermodulename'])

Here, we are creating a module name myApp and also telling the injector to inject an already available module named othermodulename.

Controller Dependency:

We can implement dependency over the controller by simply passing a service in a function, but a recommended way is to use the array notation method for controllers.

For Example:

Modulename.controller('contollername', ['$scope', 'dep1', function($scope, dep1) {
...
$scope.name = 'John';
...
}]);

Factory Dependency:

Here, we are defining factory, directives, filter with the dependency of factory function(services).

angular.module('myModule', []);
myModule.factory('serviceId', ['depService', function(depService) {
// Defining factory with a dependency of a service
}]);
myModule.directive('directiveName', ['depService', function(depService) {
// Defining directives with a dependency of a service
}]);
myModule.filter('filterName', ['depService', function(depService) {
// Defining filters with a dependency of a service
}]);

.config and .run method:

Using .config() method, we can configure a service before it will get instantiated.

config()  method can only inject providers and constant because it gets called before the service object instantiated, and at that time, there are only providers and constant available.

After completion of config, the run will get called which inject the ‘services’, ‘value’, constant as the dependencies.

Note:- We cannot inject providers using the run method.

angular.module('myModule', []);
myModule.config(['depProvider', function(depProvider) {
// We can inject other provider and constant by config method
}]);
myModule.run(['depService', function(depService) {
// We can inject service value and constant by run method
}]);

Dependency Annotation:

Dependency annotation is referred as a method to define a service name with a function so that injector will get that which service is to be injected in the function.

There are three ways to annotate a function

1. Inline Array Annotation: This is the preferable way to annotate a function with a service.

Modulename.controller('contollername', ['$scope', 'dep1', function($scope, dep1) {
...............
}]);

2. $Inject Property Annotation: we can also use $inject method to annotate a function.

var MyController = function($scope, greeter) {
...............
}
MyController.$inject = ['$scope', 'greeter'];
someModule.controller('MyController', MyController);

3. Implicit Annotation: This is the simplest way of annotating a function with a service. In this method, you only have to pass the service name as an argument of the function.

Modulename.controller('contollername',  function($scope, dep1) {
...............
});

For Example:

dependency code

Here, we are injecting service within the service and service within the controller.

Let’s create an application and implement dependencies in it.

Creating an Application:

This application will find out the square of a given number.

In this application, we will use dependency injection in service and dependency injection in the controller.

HTML File: index.html

This file shows the front view of application.

<html>
<head>
<title>Angular JS Dependency Injection</title>
<script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<link rel="stylesheet" type="text/css" href= "css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href= "css/style.css">
<script type="text/javascript" src="js/app.js"></script>
</head>
<body ng-app = "mainApp" >
<center> <h1 class="h1">AngularJS- independency injection Demo</h1> </center>
<div class="container">
<div class="demo-wrapper row">
<div class="col-md-4 col-md-offset-4 col-xs-12">
<div id="seen">
<div class="login">
<!--<h2>AngularJS Services Implementation</h2><hr><br><br>-->
<h2>Get Square Root For A Number</h2><hr/>
<div ng-controller = "CalcController">
<p>Enter a number: <input type = "number" ng-model = "number" /></p>
<button ng-click = "square()">X<sup>2</sup></button>
<p>Result: {{result}}</p>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>

JavaScript File: app.js

This is the javascript file which process the data enter by the user.

 var mainApp = angular.module("mainApp", []);
mainApp.factory('calculate', function() {
var factory = {};
factory.square = function(a, b) {
return a * b
}
return factory;
});
//============Here we are injecting a service within a service=============
mainApp.service('callcalculate', function(calculate){
this.square = function(a) {
return calculate.square(a,a);
}
});
//============here we are injecting a service within contoller=============
mainApp.controller('CalcController',function($scope, callcalculate) {
$scope.square = function() {
$scope.result = callcalculate.square($scope.number);
}
});

CSS File: style.css 

/*----------------------------------------------
css settings for HTML div exactCenter
------------------------------------------------*/
@import url(http://fonts.googleapis.com/css?family=Raleway);
.demo-wrapper{
min-height: 900px;
min-width: 300px;
}
.h1 {
margin: 40px auto !important;
}
.login h2{
background-color: #FEFFED;
text-align:center;
border-radius: 10px 10px 0 0;
margin: -10px -40px;
padding: 15px;
}
.login hr{
border:0;
border-bottom:1px solid #ccc;
margin: 10px -40px;
margin-bottom: 10px;
}
.login{
width:100%;
border-radius: 10px;
font-family:raleway;
border: 2px solid #ccc;
padding: 10px 40px 40px;
word-wrap: break-word;
}
.login p{
margin-top:8px;
font-size:16px;
}
.login hr {
margin-bottom: 30px;
}
input[type=text],input[type=number]{
width:99.5%;
padding: 10px;
border: 1px solid #ccc;
padding-left: 5px;
font-size: 16px;
font-family:raleway;
} 

Note: Here in above code, we are injecting service within a service and service within a controller in app.js file.

 Conclusion

I hope this blog will clear your concept about dependency injection in AngularJS. Please share your feedback in the space given below. Keep visiting our website for further coding tricks 🙂