2014-11-21 118 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中找到。