AngularJS $injector 依賴注入
阿新 • • 發佈:2019-01-25
推斷式注入
這種注入方式,需要在保證引數名稱與服務名稱相同。如果程式碼要經過壓縮等操作,就會導致注入失敗。
app.controller("myCtrl1", function($scope,hello1,hello2){
$scope.hello = function(){
hello1.hello();
hello2.hello();
}
});
標記式注入
這種注入方式,需要設定一個依賴陣列,陣列內是依賴的服務名字,在函式引數中,可以隨意設定引數名稱,但是必須保證順序的一致性。
var myCtrl2 = function($scope,hello1,hello2){ $scope.hello = function(){ hello1.hello(); hello2.hello(); } } myCtrl2.$injector = ['hello1','hello2']; app.controller("myCtrl2", myCtrl2);
內聯式注入
這種注入方式直接傳入兩個引數,一個是名字,另一個是一個數組。這個陣列的最後一個引數是真正的方法體,其他的都是依賴的目標,但是要保證與方法體的引數順序一致(與標記注入一樣)。
app.controller("myCtrl3",['$scope','hello1','hello2',function($scope,hello1,hello2){
$scope.hello = function(){
hello1.hello();
hello2.hello();
}
}]);
$injector常用的方法
在angular中,可以通過angular.injector()獲得注入器。
var $injector = angular.injector();
通過$injector.get('serviceName')獲得依賴的服務名字
$injector.get('$scope')
通過$injector.annotate('xxx')獲得xxx的所有依賴項
$injector.annotate(xxx)
示例程式碼:
<html>
原文地址:http://www.cnblogs.com/xing901022/p/4941166.html<head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script src="http://apps.bdimg.com/libs/angular.js/1.2.16/angular.min.js"></script> </head> <body ng-app="myApp"> <div ng-controller="myCtrl1"> <input type="button" ng-click="hello()" value="ctrl1"></input> </div> <div ng-controller="myCtrl2"> <input type="button" ng-click="hello()" value="ctrl2"></input> </div> <div ng-controller="myCtrl3"> <input type="button" ng-click="hello()" value="ctrl3"></input> </div> <script type="text/javascript"> var app = angular.module("myApp",[]); app.factory("hello1",function(){ return { hello:function(){ console.log("hello1 service"); } } }); app.factory("hello2",function(){ return { hello:function(){ console.log("hello2 service"); } } }); var $injector = angular.injector(); console.log(angular.equals($injector.get('$injector'),$injector));//true console.log(angular.equals($injector.invoke(function($injector) {return $injector;}),$injector));//true //inferred // $injector.invoke(function(serviceA){}); app.controller("myCtrl1", function($scope,hello1,hello2){ $scope.hello = function(){ hello1.hello(); hello2.hello(); } }); //annotated // function explicit(serviceA) {}; // explicit.$inject = ['serviceA']; // $injector.invoke(explicit); var myCtrl2 = function($scope,hello1,hello2){ $scope.hello = function(){ hello1.hello(); hello2.hello(); } } app.controller("myCtrl2", myCtrl2); //inline app.controller("myCtrl3",['$scope','hello1','hello2',function($scope,hello1,hello2){ // app.controller("myCtrl3",['$scope','hello1','hello2',function(a,b,c){ // a.hello = function(){ // b.hello(); // c.hello(); // } $scope.hello = function(){ hello1.hello(); hello2.hello(); } }]); //$injector.annotate()方法可以接受一個引數,引數可以是一個數組,也可以是一個數組。方法返回一個數組,陣列元素的值是在呼叫時被注入到目標函式中的服務的名稱 //下例中的myCtrl2一開始就定義為一個函式,所以輸出了其引數陣列,如果換成$injector.annotate(myCtrl3)就會提示說出錯。 console.log($injector.annotate(myCtrl2));//["$scope","hello1","hello2"] </script> </body> </html>