我經歷教程步驟5中的AngularJS,並在試驗段跨越這個片段來了:服務使用下劃線爲AngularJS測試
describe('PhoneCat controllers', function() {
describe('PhoneListCtrl', function(){
var scope, ctrl, $httpBackend;
// Load our app module definition before each test.
beforeEach(module('phonecatApp'));
// The injector ignores leading and trailing underscores here (i.e. _$httpBackend_).
// This allows us to inject a service but then attach it to a variable
// with the same name as the service.
beforeEach(inject(function(_$httpBackend_, $rootScope, $controller) {
$httpBackend = _$httpBackend_;
$httpBackend.expectGET('phones/phones.json').
respond([{name: 'Nexus S'}, {name: 'Motorola DROID'}]);
scope = $rootScope.$new();
ctrl = $controller('PhoneListCtrl', {$scope: scope});
}));
我不完全理解下劃線的目的當注射$httpBackend
。我看到評論並理解代碼正在做什麼。我只是不明白爲什麼我們只用$httpBackend
來做這件事。
我們注入的其他兩個服務與它一起,不需要這樣注入。我們如何通過以環形方式注入$httpBackend
然後立即將它分配給一個同名的變量來幫助自己,我們不能直接注入它嗎?
謝謝,我也讀了反應,但它給我的印象只是一個解釋改寫代碼中的註釋(這說明它在做什麼,而不是我們爲什麼要這麼做)。我的問題是,我們通過傳入下劃線獲得了什麼優勢,然後立即將它分配給一個相同名稱的變量,而不是直接注入(不帶下劃線)。 –
因爲使用這種技術,注入'inject'函數的'$ httpBackend'在外部範圍('describe'scope)中變得可用。 – asgoth