我正在读angularjs语音教程。我现在在步骤5上。
在“测试”一节中,我发现了以下代码:
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 in order to avoid a name conflict.
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变量。你们能解释一下吗?
提前谢谢。
发布于 2014-10-22 18:47:06
$httpBackend需要在以后的所有it测试定义中都是可访问的。因此,它必须位于it调用的父级闭包中,您将编写如下所示。
beforeEach是您处理应用于所有it调用的东西的地方,因此初始化$httpBackend是一个明智的地方。
关于上面的注释,如果inject的参数将命名为$httpBackend,那么在这个匿名函数中,您将无法访问“全局”函数(这是闭包在JavaScript中的工作方式),因此您将无法初始化它。因此,编写inject的人员添加了关于引导和尾随下划线的“神奇”功能,以便您可以将其命名与需要在内部初始化的全局变量不同。
https://stackoverflow.com/questions/26514368
复制相似问题