將服務(wù)用作控制器的依賴(lài)和將服務(wù)用作其他服務(wù)的依賴(lài)很類(lèi)似。
因?yàn)镴avascript是一種動(dòng)態(tài)語(yǔ)言,依賴(lài)注入系統(tǒng)無(wú)法通過(guò)靜態(tài)類(lèi)型來(lái)知道應(yīng)該注入什么樣的服務(wù)(靜態(tài)類(lèi)型語(yǔ)言就可以)。所以,你應(yīng)該$inject的屬性來(lái)指定服務(wù)的名字,這個(gè)屬性是一個(gè)包含這需要注入的服務(wù)的名字字符串的數(shù)組。名字要和服務(wù)注冊(cè)到系統(tǒng)時(shí)的名字匹配。服務(wù)的名稱(chēng)的順序也很重要:當(dāng)執(zhí)行工場(chǎng)函數(shù)時(shí)傳遞的參數(shù)是依照數(shù)組里的順序的。但是工場(chǎng)函數(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.angularjs.org/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依賴(lài)注入系統(tǒng)的新特性使得AngularJS可以通過(guò)參數(shù)名稱(chēng)來(lái)判斷依賴(lài)。讓們重寫(xiě)上面的例子,展示一下隱式地依賴(lài)$window, $scope:
index.html:
<!doctype html><html ng-app="MyServiceModuleDI"> <head> <script src="http://code.angularjs.org/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); };
但是如你要壓縮你的代碼,你的變量名會(huì)被重命名,你就只能顯示地指定依賴(lài)了。
Angular Service API
聯(lián)系客服