2014-11-21 96 views
1

在从Angular docs一个指令单元测试的这个例子:

describe('Unit testing great quotes', function() { 
    var $compile; 
    var $rootScope; 

    // Load the myApp module, which contains the directive 
    beforeEach(module('myApp')); 

    // Store references to $rootScope and $compile 
    // so they are available to all tests in this describe block 
    beforeEach(inject(function(_$compile_, _$rootScope_){ 
     // The injector unwraps the underscores (_) from around the parameter names when matching 
     $compile = _$compile_; 
     $rootScope = _$rootScope_; 
    })); 

    it('Replaces the element with the appropriate content', function() { 
     // Compile a piece of HTML containing the directive 
     var element = $compile("<a-great-eye></a-great-eye>")($rootScope); 
     // fire all the watches, so the scope expression {{1 + 1}} will be evaluated 
     $rootScope.$digest(); 
     // Check that the compiled element contains the templated content 
     expect(element.html()).toContain("lidless, wreathed in flame, 2 times"); 
    }); 
}); 

有人能解释什么($ rootScope)在其功能的元件变量声明在做什么。

我不确定它有什么影响。

回答

1

它用于强制$digest周期,使得它上面的元件被编译并立刻呈现,而不是等待一个未确定$digest周期

+1

如果我得到一个TypeError:undefined不是函数的错误,那该怎么办? – Daft 2014-11-21 10:17:29

1

$compile函数创建抓住从一个范围的变量值完成的功能绑定。

当您使用scope变量调用$compile创建的函数时,它会将所有绑定替换为作为参数提供的作用域上的值,然后创建一个DOM元素。

例如:在角

$rootScope.age = 15; 
$scope.age = 52; 

var element = $compile("<div>Tom is {{age}}</div>")($rootScope); 
/* element is a div with text "Tom is 15" */ 

var element2 = $compile("<div>Tom is {{age}}</div>")($scope); 
/* element2 is a div with text "Tom is 52" */ 
1

编译在两个步骤中完成。 $compile(template)只做了上半场,其中指令通常只是转换DOM(以及其他更复杂的东西),并返回一个“链接函数”。第二部分是在以特定范围作为参数调用链接函数时完成的。在这部分中,指令可以编辑范围,将行为链接到DOM事件等。更多内容可以在official guide中找到。