|
將服務(wù)用作控制器的依賴和將服務(wù)用作其他服務(wù)的依賴很類似。
因為Javascript是一種動態(tài)語言,依賴注入系統(tǒng)無法通過靜態(tài)類型來知道應(yīng)該注入什么樣的服務(wù)(靜態(tài)類型語言就可以)。所以,你應(yīng)該$inject的屬性來指定服務(wù)的名字,這個屬性是一個包含這需要注入的服務(wù)的名字字符串的數(shù)組。名字要和服務(wù)注冊到系統(tǒng)時的名字匹配。服務(wù)的名稱的順序也很重要:當執(zhí)行工場函數(shù)時傳遞的參數(shù)是依照數(shù)組里的順序的。但是工場函數(shù)中參數(shù)的名字不重要,但最好還是和服務(wù)本身的名字一樣,下面展示了這樣的好處:formatDate
function myController($loc, $log) {
this.firstMethod = function() {
// use $location service
$loc.setHash();
};
this.secondMethod = function() {
// use $log service
$log.info('...');
};
}
// which services to inject ?
myController.$inject = ['$location', '$log'];
index.html:
<!doctype html>
<html ng-app="MyServiceModule">
<head>
<script src="http://code./angular-1.0.2.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<div ng-controller="myController">
<p>Let's try this simple notify service, injected into the controller...</p>
<input ng-init="message='test'" ng-model="message" >
<button ng-click="callNotify(message);">NOTIFY</button>
</div>
</body>
</html>
script.js:
angular.
module('MyServiceModule', []).
factory('notify', ['$window', function(win) {
var msgs = [];
return function(msg) {
msgs.push(msg);
if (msgs.length == 3) {
win.alert(msgs.join("\n"));
msgs = [];
}
};
}]);
function myController(scope, notifyService) {
scope.callNotify = function(msg) {
notifyService(msg);
};
}
myController.$inject = ['$scope','notify'];
end to end test:
it('should test service', function() {
expect(element(':input[ng\\:model="message"]').val()).toEqual('test');
});
隱式依賴注入
AngularJS依賴注入系統(tǒng)的新特性使得AngularJS可以通過參數(shù)名稱來判斷依賴。讓們重寫上面的例子,展示一下隱式地依賴$window, $scope:
index.html:
<!doctype html>
<html ng-app="MyServiceModuleDI">
<head>
<script src="http://code./angular-1.0.2.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<div ng-controller="myController">
<p>Let's try the notify service, that is implicitly injected into the controller...</p>
<input ng-init="message='test'" ng-model="message">
<button ng-click="callNotify(message);">NOTIFY</button>
</div>
</body>
</html>
script.js:
angular.
module('MyServiceModuleDI', []).
factory('notify', function($window) {
var msgs = [];
return function(msg) {
msgs.push(msg);
if (msgs.length == 3) {
$window.alert(msgs.join("\n"));
msgs = [];
}
};
});
function myController($scope, notify) {
$scope.callNotify = function(msg) {
notify(msg);
};
但是如你要壓縮你的代碼,你的變量名會被重命名,你就只能顯示地指定依賴了。
相關(guān)主題
- 理解AngularJS服務(wù)
- 創(chuàng)建AngularJS服務(wù)
- 管理服務(wù)依賴
- 測試AngularJS服務(wù)
相關(guān)API
Angular Service API
|