AngularJS Dependency Injection

The term 'Dependency Injection' in the field of software engineering, refers to a software design pattern that uses inversion of control to resolve dependency. Here, a dependency is a reference to an object or a service which can be used and an injection is referred to passing off this dependency to the dependent object for it to use. To put it in simple terms, the fundamentals of this pattern are directed towards passing off a service to the client instead of making the client build or search for the service.

In AngularJS, the term refers to a software design pattern as well. In this pattern, the components are not hard coded within, but are given dependencies. This makes the dependencies to be configurable and does not need the component to locate the dependency.

AngularJS, having a vibrant Dependency Injection method has a few core components which can be injected as dependencies into each other. They are:


  • value
  • factory
  • service
  • provider
  • constant

Let us have a look at each of these individually.


value

During the configuration phase, this is used to pass values to the controller. It is nothing but a simple javascript object.

//define a module  
var newModule = angular.module("newModule", []);  
//create a value object and pass it a data.   
newModule.value("numberValue", 1000);  
newModule.value("stringValue", "abcd");  
newModule.value("objectValue", { val1 : 1234, val2 : "abcd"} );  

factory

When a service or controller requires and demands a value, the factory creates a value. factory is nothing but a function which is used to return values. The factory function is used to calculate and return the values generally.

var newModule = angular.module("newModule", []);  
newModule.factory("myFactory", function() {  
    return "a value";  
});  
newModule.controller("MyController", function($scope, myFactory) {  
console.log(myFactory);  
});  

service

Before being injected into the controllers, services are generally defined using service() function. It is used to perform certain tasks and generally has a set of functions in a singleton javascript object.

//define a module  
var mainApp = angular.module("mainApp", []);  
...  
//create a service which defines a method square to return square of a number.  
mainApp.service('CalcService', function(MathService){  
   this.square = function(a) {  
      return MathService.multiply(a,a);   
   }  
});  
//inject the service "CalcService" into the controller  
mainApp.controller('CalcController', function($scope, CalcService, defaultInput) {  
   $scope.number = defaultInput;  
   $scope.result = CalcService.square($scope.number);  
    $scope.square = function() {  
      $scope.result = CalcService.square($scope.number);  
   }  
});  

provider

provider is used to return a value or service or factory with a method get() function. It is a special factory method that is used. During the configuration phase which is a phase in which AngularJS bootstraps itself, it internally uses the provider to generate services, factory, etc.

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

constant

It needs to be noted that value cannot be taken up to use to pass during the configuration stage. Hence, we have constants. There constants are basically used to pass off the values during the configuration stage since we cannot use value as mentioned.

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

 <!DOCTYPE html>  
<html>  
   <head>  
      <title>AngularJS Dependency Injection Example</title>  
   </head>  
   <body>  
      <h2>AngularJS Sample Application</h2>  
        
      <div ng-app = "mainApp" 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>  
        
      <script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>  
        
      <script>  
         var mainApp = angular.module("mainApp", []);  
           
         mainApp.config(function($provide) {  
            $provide.provider('MathService', function() {  
               this.$get = function() {  
                  var factory = {};  
                    
                  factory.multiply = function(a, b) {  
                     return a * b;  
                  }  
                  return factory;  
               };  
            });  
         });  
              
         mainApp.value("defaultInput", 10);  
           
         mainApp.factory('MathService', function() {  
            var factory = {};  
              
            factory.multiply = function(a, b) {  
               return a * b;  
            }  
            return factory;  
         });  
           
         mainApp.service('CalcService', function(MathService){  
            this.square = function(a) {  
               return MathService.multiply(a,a);  
            }  
         });  
           
         mainApp.controller('CalcController', function($scope, CalcService, defaultInput) {  
            $scope.number = defaultInput;  
            $scope.result = CalcService.square($scope.number);  
  
            $scope.square = function() {  
               $scope.result = CalcService.square($scope.number);  
            }  
         });  
          </script>  
      </body>  
</html>