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.

Example:

<html>
 
   <head>
     <title>AngularJS Dependency Injection Example</title>
     <script src=
      "http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js">
     </script>
   </head>
 
   <body>
      <h2>AngularJS Dependency Injection Example</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>
         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);
            }
         });
 
         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>

Try it:

AngularJS Dependency Injection Example on jsbin.com