Latest web development tutorials

AngularJS dependency injection

What is Dependency Injection

Explanation on the wiki are: dependency injection (Dependency Injection, abbreviated DI) is a software design pattern, in this mode, one or more dependent (or service) is injected (or passed by reference) to an independent Object (or client), and then became part of the client state.

The model separates clients rely on itself to create a behavior, which makes the program design becomes loosely coupled, and follows the Dependency Inversion principle of single and responsibilities. Service Locator pattern formation and a direct comparison is that it allows the client to understand how clients use the system to find the dependence

A word --- nothing you do not come to me, I'll find you something.

AngularJS provide a good mechanism for dependency injection. The following five core components used as dependency injection:

  • value
  • factory
  • service
  • provider
  • constant

value

Value is a simple javascript object, pass a value to the controller (configuration phase) to:

// 定义一个模块
var mainApp = angular.module("mainApp", []);

// 创建 value 对象 "defaultInput" 并传递数据
mainApp.value("defaultInput", 5);
...

// 将 "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 a function that returns a value. Create and controller at the time of service needs.

Usually we use to calculate or factory function return values.

// 定义一个模块
var mainApp = angular.module("mainApp", []);

// 创建 factory "MathService" 用于两数的乘积 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;
}); 

// 在 service 中注入 factory "MathService"
mainApp.service('CalcService', function(MathService){
   this.square = function(a) {
      return MathService.multiply(a,a);
   }
});
...

provider

AngularJS created by a provider service, factory, etc. (configuration phase).

Provider provides a factory method get (), which returns the value / service / factory.

// 定义一个模块
var mainApp = angular.module("mainApp", []);
...

// 使用 provider 创建 service 定义一个方法用于计算两数乘积
mainApp.config(function($provide) {
   $provide.provider('MathService', function() {
      this.$get = function() {
         var factory = {};  
         
         factory.multiply = function(a, b) {
            return a * b; 
         }
         return factory;
      };
   });
});

constant

constant (constant) used to pass values ​​in the configuration phase, constant attention to this stage in the configuration is not available.

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

Examples

The following examples provide more than several dependency injection mechanism demonstration.

<html>
   
   <head>
      <meta charset="utf-8">
      <title>AngularJS  依赖注入</title>
   </head>
   
   <body>
      <h2>AngularJS 简单应用</h2>
      
      <div ng-app = "mainApp" ng-controller = "CalcController">
         <p>输入一个数字: <input type = "number" ng-model = "number" /></p>
         <button ng-click = "square()">X<sup>2</sup></button>
         <p>结果: {{result}}</p>
      </div>
      
      <script src="http://apps.bdimg.com/libs/angular.js/1.4.6/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>

try it"