Easy learning with example program codes

Angularjs dependency injection tutorial

Dependency Injection (DI):

Dependency Injection (DI) is a design pattern that implements inversion of control principle for resolving dependencies. It allows a programmer to remove hard coded dependencies so that the application becomes loosely coupled and extendable

AngularJS dependency injection:

AngularJS provides also provides the mechanism of Dependency Injection with the help of following core components which can be injected into each other as dependencies.

1. value: Represents a javascript object which is used to pass values to controller during config phase.
2. factory: Represents a function which is used to return value.
3. service: Represents a function or object which is used to perform specific task.
4. provider: It is used by AngularJS internally to create services, factory etc during config phase.
5. constant: Constants are used to pass values at config phase.

Note: Config phase: It represents a phase during which AngularJS bootstraps itself.


     <title>AngularJS Dependency Injection Example</title>
     <script src=
      <h2>AngularJS Dependency Injection Example</h2>
      <div ng-app = "mainApp" ng-controller = "CalcController">
         <p>Enter a number: <input type = "number" ng-model = "number" />
         <button ng-click = "square()">X<sup>2</sup></button>
         <p>Result: {{result}}</p>
         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", 5);
         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);
                   function($scope, CalcService, defaultInput) {
            $scope.number = defaultInput;
            $scope.result = CalcService.square($scope.number);
            $scope.square = function() {
               $scope.result = CalcService.square($scope.number);

Try it:

AngularJS Dependency Injection Example on

Industrial Training

We offers Placement Oriented Training on Java, Spring, JSF, Hibernate, PHP, AngularJS, Angular 4, PLSQL, Oracle BI Publisher etc. We also provides Online training, please mail us at


We also provides the Development services for Website Development , Java Development, PHP Development, Android App Development etc. You can contact us on

Copyright © 2019 CodesJava Protection Status SiteMap Reference: Java Wiki