AngularJS為我們提供了angular.injector(modules)
DI注入注射器。但是在我們使用注入的時(shí)候常常是不需要關(guān)心具體的如何注入。我們只需要按照其規(guī)則書寫我們的angularjs代碼就會(huì)很容易的得到angularjs的DI特性。
一般有三種方法來做依賴注入。
在angularjs中我們可以在我們需要注入的地方按照名稱注入,這里要求參數(shù)名稱必須和注入服務(wù)實(shí)例名稱相同,一種名稱約定。angularjs會(huì)提取參數(shù)名稱查找相應(yīng)DI實(shí)例注入。
var myModule = angular.module('myModule', []);
myModule.factory('$alert', function($window) {
return {
alert: function(text) {
$window.alert(text);
}
};
});
var myController = function($scope, $alert) {
$scope.message = function(msg) {
console.log(msg);
$alert.alert(msg);
};
};
myModule.controller("myController", myController);
在angularjs中我們可以利用$inject標(biāo)注DI注入,這里需要注入服務(wù)名稱的順序和構(gòu)造參數(shù)名對(duì)應(yīng).這里可以解決以上約定的死板性。
var myModule = angular.module('myModule', []);
myModule.factory('$alert', ['$window', function($window) {
return {
alert: function(text) {
$window.alert(text);
}
};}]);
var myController = function($scope, $alert) {
$scope.message = function(msg) {
console.log(msg);
$alert.alert(msg);
};
};
myController.$inject = ['$scope', '$alert'];
myModule.controller("myController", myController);
在這里,
var myController = function($scope, $alert) {
$scope.message = function(msg) {
console.log(msg);
$alert.alert(msg);
};
};
我們可以將$scope
和$alert
改為任意的參數(shù)名,但是myController.$inject = ['$scope', '$alert'];
是必須要有的,且數(shù)組的元素與實(shí)際的服務(wù)名一致,順序與controller中的參數(shù)順序一致。
對(duì)于directives,factory,filter等特殊指令使用$inject
標(biāo)注注入使用不是那么友好,angularjs特別增加了內(nèi)聯(lián)注入。如上面的$alert
服務(wù)。
myModule.factory('$alert', ['$window', function($window) {
return {
alert: function(text) {
$window.alert(text);
};
}]);
這里的$window
就是采用內(nèi)聯(lián)注入的方式。同樣的道理,在一些工廠方法中,比如controller、directive等,也可以采取這種方式來依賴注入。
angular.module('app', [])
.controller('controllerName', [
'dep1',
'dep2',
...,
function(dep1, dep2, ...) {
...
}
]);
更多建議: