Home >Web Front-end >JS Tutorial >Detailed explanation of dependency injection mechanism in AngularJS_AngularJS

Detailed explanation of dependency injection mechanism in AngularJS_AngularJS

WBOY
WBOYOriginal
2016-05-16 15:54:301124browse

Dependency injection is a software design pattern that replaces hard coding of their dependencies within components by giving them in components. This relieves one component, from locating dependencies, to dependency configuration. This helps make components reusable, maintainable and testable.

AngularJS provides a supreme dependency injection mechanism. It provides the following core components that can inject dependencies on each other.

  • Value
  • Factory
  • Service
  • Provider
  • Constant value

Value

Values ​​are simple JavaScript objects that are used to pass values ​​during configuration phase controllers.

//define a module
var mainApp = angular.module("mainApp", []);
//create a value object as "defaultInput" and pass it a data.
mainApp.value("defaultInput", 5);
...
//inject the value in the controller using its name "defaultInput"
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);
  }
});

Factory

Factory is used to return the value of the function. It creates value on demand, whenever a service or controller requires it. It usually uses a factory function to calculate and return the corresponding value

//define a module
var mainApp = angular.module("mainApp", []);
//create a factory "MathService" which provides a method multiply to return multiplication of two numbers
mainApp.factory('MathService', function() {   
  var factory = {}; 
  factory.multiply = function(a, b) {
   return a * b 
  }
  return factory;
}); 

//inject the factory "MathService" in a service to utilize the multiply method of factory.
mainApp.service('CalcService', function(MathService){
   this.square = function(a) { 
   return MathService.multiply(a,a); 
  }
});
...

Service

A service is a single JavaScript object that contains a set of functions to perform certain tasks. Services are defined using the service() function, which is then injected into the controller.

//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 services, factories, etc. used during the configuration phase of the AngularJS internal creation process (corresponding to when AngularJS bootstraps itself). The script mentioned below can be used to create the MathService we have already created earlier. The provider is a special factory method and get() method that returns a value/service/factory.

//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

Constants are used to account for the fact that values ​​cannot be passed during the configuration phase by configuring them, and values ​​cannot be passed during the configuration phase.

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

Example

The following example will demonstrate all the above commands.
testAngularJS.html

<html>
<head>
  <title>AngularJS Dependency Injection</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" />
   <button ng-click="square()">X<sup>2</sup></button>
   <p>Result: {{result}}</p>
  </div>
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/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", 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>

Results

Open textAngularJS.html in your web browser. See the results below.

2015617111816048.jpg (560×240)

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn