1、定義html
如前所述,$scope對象被神祕的注入到了控制器中,實際上,這是由於控制器聲明瞭它須要$scope,因此AngularJS纔會建立並注入它。這套依賴管理系統能夠這樣總結:"爲了正常工做,我須要一個依賴(協做對象):我不知道它從哪裏來,也不知道它如何建立。我只知道我須要它,因此請爲我提供它"。angularjs
AngularJS擁有內建的依賴注入(dependeny injection,DI)引擎,職責以下:yii
2、註冊服務ide
AngularJS只鏈接其認識的對象。所以,接入依賴注入機制的第一步,是將對象註冊在模塊(module)上。咱們不直接註冊對象的實例,而是將對象建立方案拋給依賴注入系統。而後AngularJS解釋這些方案以初始化對象,並在以後鏈接他們,最後成爲可運行的項目。this
AngularJS的$provide服務能夠註冊不一樣的對象建立方案。以後$injector服務會解釋這些方案,生成完備而可用的對象實例(已經解決好全部的依賴關係)。spa
$injector服務建立的對象成爲服務(service)。在整個應用的生命中,每種方案AngularJS僅解釋一次,也就是說,每一個對象僅有一個實例。code
http://www.yiibai.com/angularjs/angularjs_dependency_injection.htmlhtm
五種對象建立方案:對象
2.1 值blog
定義一個名爲defaultInput值,能夠注入到控制器中
// 定義一個模塊 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); } });
2.2 服務
定義一個名爲CalcService的服務,能夠注入到控制器中
//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); } });
2.3 Factory
//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); } }); ...
2.4 常量
mainApp.constant("configParam", "constant value");
2.5 Provider
//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; }; }); });