For enquiries call:

Phone

+1-469-442-0620

April flash sale-mobile

HomeBlogWeb DevelopmentDependency Injection in AngularJS

Dependency Injection in AngularJS

Published
05th Sep, 2023
Views
view count loader
Read it in
12 Mins
In this article
    Dependency Injection in AngularJS

    AngularJS is an open source JavaScript MVW (Model View Whatever) framework backed by Google and is widely popular for creating dynamic apps. It offers a suite of tools that can be used for building the framework most suited to your single page application development. However, it can also be fully utilized to work for other categories of web pages. It works well with other web-based libraries and is fully extensible. All its features can be modified and even can be replaced to suit your unique development workflow and web feature needs.    

    As AngularJS is a pure JavaScript framework, it can be added to an HTML page with a normal <script> tag with src attribute pointing to the source framework library, just like other JavaScript libraries.  

    AngularJS extends HTML attributes using Directives.  It binds data to HTML using Expressions. 

    AngularJS can be downloaded from. 

    If you’re new to AngularJS, it is better to get introductory information from. This site provides the basic information required to start working with AngularJS. 

    It has various features including MVC ArchitectureDirectivesExpressionsControllersFiltersHTML DOMModules, Views, AJAXScopesServicesDependency Injection, and Internationalization. We will deal with Dependency Injection in the following section. 

    Get to know more about angular cli.

    Introduction

    Dependency Injection − AngularJS has a built-in dependency injection (DI) subsystem library whose work is to help the development team by making the application easier to develop, test, and understand. We will learn about each part of DI in detail. 

    The topics we will go through in this article are: 

    Dependency injection in AngularJS 

    • Value 
      • Injecting a Value 
    • Factory 
      • Injecting Values into a Factory 
    • Service 
      • Injecting Values into a Service 
    • Providers 
      • Configuring a Provider 
    • Constants 
      • Dependencies Between Modules 

    Dependency injection in AngularJs 

    Today’s software is totally designed in accordance with various design patterns. One such pattern is Dependency Injection. The DI design pattern specifies the pattern in which components are provided with their dependencies, instead of hard coding them within the component. 

    AngularJS comes with a built-in dependency injection mechanism that enables you to divide your application into various types of components which can be injected into each other as their respective dependencies. 

    Modularization of your application makes it easier to use, reuse, configure and even test the different components in your application. According to DI the core types of objects and components include the following: 

    • Value 
    • Factory 
    • Service 
    • Provider 
    • Constant 

    These are the objects and components which can be injected into each other using AngularJS Dependency Injection. 

    Value

    For AngularJSthe “Value is a simple object. It can be a number, string or a POJO (Plain old JavaScript object)This object is used to pass values in AngularJS factories, AngularJS services or AngularJS controllers during the run and config phase. The following example shows the steps involved in using a value. 

    Step 1:  Define a module   

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

    Here, myModule is created using the AngularJS function angular.module(). You can add value, controllers, directives, filters, and more, to your AngularJS application using a module. 

    Step 2: Create a value object and pass data to it.    

    myMod.value("numberValue", 10);   
    myMod.value("stringValue", "aaa");   
    myMod.value("objectValue", { field1 : 123, field2 : "abc"} );  

    Here, values are defined using the value () function on the module as created in step 1. The first parameter specifies the name of the value, and the second parameter is the value itself passed to other parts of the application. Factories, services and controllers can now reference these values by their value name. 

    Step 3: Injecting a value in Controller function 

    To inject a value into AngularJS controller function, we need to add a parameter with the same value name as that with which the value was defined. Note that the controller function is registered in angular via the angular.module(...).controller(...) function call. The $scope parameter passed to the controller function is the model for the controller. Thus, here myMod is the module registering the controller as myController, and $scope is the model for myController 

    var myMod = angular.module("myModule", []);   
    myMod.value("numberValue", 10);   
    myMod.controller("myController", function($scope, numberValue) {   
     console.log(numberValue);   
    });

    Example: Using Value in AngularJS: 

    Consider that you have already downloaded the latest AngularJS file from (here we are using the minified version of AngularJS as angular.min.js). We can even use the AngularJs CDN for the same provided by Google. 

    <! DOCTYPE html> 
    <html> 
    <head> 
     <meta charset = "UTF-8"> 
    <title> Value in AngularJS </title> 
    </head> 
    <script src = "angular.min.js"> 
    </script> 
    <body ng-app = "myModule"> 
    <div ng-controller = "myController"> 
    <h3> Value Example </h3>  
    <h1> The numberValue is: {{nValue}} 
    <h1> 
    </div> 
    <script> 
    var myMod = angular.module('myModule', []); 
    myMod.value("numberValue", 5); 
    myMod.controller('myController', function($scope, numberValue 
    { 
    $scope.nValue =numberValue; 
    }); 
    </script> 
    </body> 
    </html> 

    Output: 

    What Is Dependency Injection in AngularJS

    Factory 

    In AngularJSa factory is a function that is used to return value. This function creates the value on demand whenever a service or controller needs any value injected from the factory. AngularJS applications normally use a factory function to calculate and return a value. The following example shows the steps involved in using a Factory. 

    Step 1:  Define a module   

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

    Here, myModule is created using the AngularJS function angular.module(). You can add factory, value, controllers, directives, filters, and more, to your AngularJS application using a module. 

    Step 2: Create a factory object and return data from it.    

    myMod.factory("myFactory", function() {   
        return "a value";   
    }); 

    Here, we have used the factory function to create a Factory named myFactory. This Factory is returning “a value” from it. 

    Step 3: Injecting values into factory 

    Create a controller which gets the factory created value injected (for explanation of Controller, go to the Value part of the article and navigate to its Step 3)To inject a factory value into AngularJS controller function, we need to add a parameter with the same value name as that with which the factory was defined.  

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

    Note: It is not the factory function that is injected, but the value produced by the factory function that gets injected. 

    Example: Using Factory in AngularJS: 

    <! DOCTYPE html> 
    <html> 
    <head> 
    <meta charset="UTF-8"> 
    <title> Factory </title> 
    </head> 
    <script src = "angular.min.js"> </script> 
    <body ng-app = "myModule"> 
    <div ng-controller = "myController"> 
        <h3> Factory Example </h3> 
    <h1> The numberFactory is: {{nFactory}} 
    <h1> 
    </div> 
    <script> 
    var myMod = angular.module('myModule', []); 
    myMod.factory("myFactory", function() {   
    return "a value";   
    });   
        myMod.controller('myController', function($scope, myFactory) { 
    $scope. nFactory =myFactory; 
    }); 
    </script> 
    </body> 
    </html> 

    Output: 

    What Is Dependency Injection in AngularJS

    Service 

    Web Services are helpful functions that perform a task. Similarly, in AngularJS, Service is a JavaScript object which contains a set of functions to perform certain tasks. Services are created by using service() function on a module and then injecting it into controllers. The following example shows the steps involved in using a Service. 

    Step 1:  Define a module   

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

    Here, myModule is created using the AngularJS function angular.module(). You can add Services, factory, value, controllers, directives, filters, and more, to your AngularJS application using a module. 

    Step 2: Create a service for defining the MathService for calculating basic math functions like add, subtract, multiply and divide. And then create another service, myService for defining a cube method to return the cube of a given number: 

    myMod.service('MathService', function() { 
        this.add = function(a, b) { return a + b }; 
        this.subtract = function(a, b) { return a - b }; 
        this.multiply = function(a, b) { return a * b }; 
        this.divide = function(a, b) { return a / b }; 
    }); 
    myMod.service('myService', function(MathService){   
       this.cube = function(a) {   
          return MathService.multiply(a,MathService.multiply(a,a));    
       }   
    }); 

    The above code snippet uses MathService to call multiply function that takes two parameters and calculates the product.  

    Step 3: Inject the service "myService" into the controller   

    Create a controller which gets the Service injected (for explanation of Controller, go to the Value part of the article and navigate to its Step 3). To inject a Service function into AngularJS controller function, we need to add a parameter with the same value name as that with which the Service was defined.  

    myMod.controller('myController', function($scope, myService) {   
        $scope.doCube = function() {   
          $scope.result = myService.cube($scope.number);   
       }   
    }); 

    Here we can even make it event based by adding an event in the main HTML content as: 

    <div ng-app = "myModuleng-controller = "myController"> 
    Enter a number: 
            <input type="number" ng-model="number" /> 
    <button ng-click="doCube()"> Cube </button> 
    <p>  
    <h1> Result of Service: {{result}} <h1> 
    </p> 
    </div> 

    Example: Using Service in AngularJS: 

    <! DOCTYPE html> 
    <html> 
    <head> 
    <meta charset="UTF-8"> 
    <title> Service Example </title> 
    </head> 
    <script src = "angular.min.js"> 
    </script> 
    <body> 
    <h3> Service Example </h3> 
    <div ng-app = "myModuleng-controller = "myController"> 
    <p>  
    <h1> Result of Service: {{result}} <h1> 
    </p> 
    </div> 
     <script> 
    var myMod = angular.module("myModule", []); 
    myMod.service('myService', function(){ 
    this.sum = function(a,b) { 
    return a + b; 
    }     
    }); 
    myMod.controller('myController', function($scope, myService) { 
    $scope.result = myService.sum (5, 6); 
    }); 
    </script> 
    </body> 
    </html> 

    Output: 

    What Is Dependency Injection in AngularJS

    Provider 

    In AngularJSa provider is used to internally create other values or services or factory during config phase (the phase during which AngularJS bootstraps itself). Provider can be considered to be the most flexible form of factory you can create. Provider is a special factory method with a get() function which is used to return the value or service or factory. The following example shows the steps involved in using a Provider. 

    Step 1:  Define a module   

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

    Here, myModule is created using the AngularJS function angular.module(). You can add Services, factory, value, controllers, directives, filters, and more, to your AngularJS application using a module. 

    Step 2: Create a service using provider which defines a method square to return the square of a number.  We use provider method to create a Provider.   

    myMod.config(function($provide) {   
       $provide.provider('myServiceProvider', function() {   
          this.$get = function() {   
             var factory = {};     
             factory.multiply = function(a, b) {   
                return a * b;    
             }   
             return factory;   
          };   
       });   
    }); 
    
    

    Step 3: Inject the Provider "myServiceProvider" into the controller   

    Create a controller which gets the Provider injected (To understand how to create a Controller, go to the Value part of the article and navigate to its Step 3). To inject a Provider function into AngularJS controller function, we need to add a parameter with the same value name as that with which the provider was defined.  

    myMod.controller('myController', function($scope, myServiceProviderdefaultInput) {   
        $scope.number = defaultInput;   
        $scope.result = myServiceProvider.multiply($scope.number$scope.number);   
        $scope.square = function() {   
               $scope.result = myServiceProvider.multiply($scope.number$scope.number);    
        }      
    });   

    Example: Using Provider in AngularJS: 

    <!DOCTYPE html>   
    <html>    
    <head>    
    <title> Provider </title>    
    </head>   
       <body>   
    <h2> Provider Example </h2>   
           <div ng-app = "myModuleng-controller = "myController">   
             <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 = "angular.min.js"> </script>     
    <script>   
             var myMod  = angular.module("myModule", []);   
              myMod.config(function($provide) {   
    $provide.provider('myServiceProvider', function() {   
    this.$get = function() {   
    var factory = {};   
    factory.multiply = function(a) {    
    return a * a;         
    } 
    return factory;     
    };       
    });    
     });   
             myMod.value("defaultInput", 10);   
             myMod.controller('myController', function($scope, myServiceProviderdefaultInput) {   
                $scope.number = defaultInput;   
                $scope.result = myServiceProvider.multiply($scope.number);   
    $scope.square = function() {   
    $scope.result = myServiceProvider.multiply($scope.number);    
    }       
    });   
    </script>        
    </body> 
    </html> 

    Output: 

    What Is Dependency Injection in AngularJS

    Constants 

    Config Phase of AngularJS has some restrictions for injected values, as you cannot inject values into the module.config() function. Instead constants are used to pass values at config phase. To define a constant value we use the constant() function of the defined module. Then for the constant parameter we provide a constant value. The following example shows the steps involved in using a Constant in AngularJS. 

    Step 1: Define a module   

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

    Here, myModule is created using the AngularJS function angular.module(). You can add Services, factory, value, controllers, directives, filters, and more, to your AngularJS application using a module. 

    Step 2: Create a constant using the constant function and pass constant data to it.      

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

    Example: Using Constant in AngularJS: 

    <! DOCTYPE html> 
    <html> 
    <head> 
    <meta charset="UTF-8"> 
        <title> Constant </title> 
    </head> 
    <script src = "angular.min.js"> </script> 
    <body ng-app = "myModule"> 
    <div ng-controller = "myController"> 
    <h3> Constant Example </h3>   
    <h1> The numberConstant is:  {{nConstant}} 
    <h1> 
    </div> 
    <script> 
        var myMod = angular.module('myModule', []); 
        myMod.constant("nConst", 5); 
        myMod.controller('myController', function($scope,nConst) { 
    $scope.nConstant =nConst; 
    }); 
    </script> 
    </body> 
    </html>  

    Output: 

    What Is Dependency Injection in AngularJS

    Difference between Constant and Value 

    Values and Constants seem to be applied in the same way; however, Value differs from Constant in that value cannot be injected into configurations, but it can be intercepted by decorators. Also, Constant can be used during the apps config phase, whereas a Value is only available during the run phaseThe main difference between value and constant is that a value specified using Constant is available during the configuration phase while value specified using Value is available during the run phase. 

    Example showing the difference between a Constant and a Value: 

    <! DOCTYPE html> 
    <html> 
    <head> 
    <meta charset="UTF-8"> 
    <title> Constant </title> 
    </head> 
    <script src = "angular.min.js"> 
    </script> 
    <body ng-app="myModule"> 
    <div ng-controller="myController"> 
        <h3> Constant Example</h3>   
    {{ID}} 
    </div> 
    <script> 
        var myMod = angular.module('myModule', []); 
    myMod.value("myValue", "First Assignment"); 
    myMod.value("myValue", "Second  Assignment"); 
    myMod.constant("myConstant", "First Assignment"); 
    myMod.constant("myConstant", "Second Assignment"); 
    myMod.controller("myController", function($scope, myValuemyConstant) { 
    console.log("myValue: " + myValue); 
    console.log("myConstant: " + myConstant); 
    $scope.ID = myValue: " + myValue + "&nbsp   myConstant: " + myConstant; 
    }); 
    </script> 
    </body> 
    </html> 

    Output: 

    Constant Example 

    myValue: Second Assignment myConstant: First Assignment  

    Complete Example: AngularJS Dependency Injection 

    Let's take an example to deploy all the above mentioned directives. 

    <!DOCTYPE html>   
    <html>    
    <head>   
       <title> AngularJS Dependency Injection </title>    
    </head>   
       <body>   
    <h2> AngularJS Application Showing Dependency Injection </h2>   
    <div ng-app = "myModng-controller = "myController">   
    <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 = "angular.min.js"> 
    </script>   
    <script>   
    var myMod = angular.module("myMod", []);   
    myMod.config(function($provide) {   
    $provide.provider('MathService', function() {   
    this.$get = function() {   
    var factory = {};   
    factory.multiply = function(a, b) {   
    return a * b;         
    }   
    return factory;     
    };       
    });     
    });   
    myMod.value("defaultInput", 10);   
    myMod.factory('MathService', function() {   
                var factory = {};   
                factory.multiply = function(a, b) {   
    return a * b; 
    }   
    return factory; 
    }); 
             myMod.service('CalcService', function(MathService){   
    this.square = function(a) {   
    return MathService.multiply(a,a);    
    }        
    });   
    myMod.controller('myController', function($scope, CalcServicedefaultInput) {   
    $scope.number = defaultInput;   
    $scope.result = CalcService.square($scope.number);   
    $scope.square = function() {   
    $scope.result = CalcService.square($scope.number);     
    }       
    });   
    </script>        
    </body> 
    </html> 

    Output: 

    What Is Dependency Injection in AngularJS

    Unlock Your Potential with our Programming Basic Course! Learn the Fundamentals and Master the Art of Coding. Enroll Today for a Bright Future in Tech. Join Now!

    Conclusion

    In the above article we learned about the Dependency Injection in AngularJS. Dependency Injection is a software design pattern that specifies how components get hold of their dependencies. In this pattern, components are given their dependencies instead of coding them directly within the component. 

    We learned about core types of objects and components like Value, Factory, Service, Provider, and Constant. We learned how to create and register an injectable service and configure an injector with a service provider. We learned how to work withInjecting services to a controller. 

    In the end we summarized with a complete example how Providers, Services, Factory and Value can be used.  

    Note: Angular is a version upgrade to AngularJS. Therefore, Angular refers to AngularJS in this article.

    Profile

    Monica Gupta

    Author

    I am Monica Gupta with 19+ years of experience in the field of Training and Development. I have done over 500 Corporate Trainings. I am currently working as a freelancer for several years. My core area of work is Java, C++, Angular, PHP, Python, VBA.

    Share This Article
    Ready to Master the Skills that Drive Your Career?

    Avail your free 1:1 mentorship session.

    Select
    Your Message (Optional)

    Upcoming Web Development Batches & Dates

    NameDateFeeKnow more
    Course advisor icon
    Course Advisor
    Whatsapp/Chat icon