当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - angularjs phonecat tutorial step 5

问题描述:

I am reading the angularjs phonecat tutorial. I am currently on the step 5.

In the section "Test", I've found this piece of code:

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});

}));

I can't understand the reason to create the $httpBackend var. Can you guys explain me?

Thanks in advance.

网友答案:

$httpBackend needs to be accessible in all it test definitions later on. Thus it has to be in a parent closure of the it calls you'll write bellow.

beforeEach is the place where you do stuff that applies to all it calls so it is a sensible place to initialize $httpBackend.

Regarding the comment above it, if the parameter to inject would be named $httpBackend then inside that anonymous function you wouldn't have access to the "global" one (that's how closures work in JavaScript), so you would not be able to initialize it. Thus the people who wrote inject added this "magic" functionality regarding leading and trailing underscores, so that you can name it differently from the global variable that you need to initialize inside.

I'd recommend reading this to better understand closures.

分享给朋友:
您可能感兴趣的文章:
随机阅读: