2014-01-31 46 views
5

我正在寫一個指令測試,執行測試模板(這是正確加載)時,只呈現爲<!-- ng-repeat="foo in bar" -->

對於初學者的相關部分代碼:

測試

... 

beforeEach(inject(function ($compile, $rootScope, $templateCache) { 

    var scope = $rootScope; 
    scope.prop = [ 'element0', 'element1', 'element2' ]; 

    // Template loading, in the real code this is done with html2js, in this example 
    // I'm gonna load just a string (already checked the problem persists) 
    var template = '<strong ng-repeat="foo in bar"> <p> {{ foo }} </p> </strong>'; 
    $templateCache.put('/path/to/template', [200, template, {}]); 

    el = angular.element('<directive-name bar="prop"> </directive-name>'); 
    $compile(el)(scope); 
    scope.$digest(); // <--- here is the problem 
    isolateScope = el.isolateScope(); 

    // Here I obtain just the ng-repeat text as a comment 
    console.log(el); // <--- ng-repeat="foo in bar" --> 
})); 

... 

指令

該指令是相當簡單的,它是沒有問題的(外測試一切正常就好了):

app.directive('directiveName', function() { 
    return { 
     restrict : 'E', 
    replace : true, 
    scope : { 
     bar : '=' 
    }, 
    templateUrl : '/path/to/template', // Not used in this question, but still... 
}); 

的詳細原因:

  • 該指令,測試外,正常工作
  • 如果我將模板更改爲如下簡單的東西:<h3> {{ bar[0] }} </h3>測試工作正常
  • rootScope是l oaded正確
  • 的isolateScope結果undefined

回答

2

如果你看一下生成的輸出角創建ng-repeat你會發現在你的HTML註釋。例如:

<!-- ngRepeat: foo in bars --> 

這些意見將由編譯函數創建 - 見角來源:

document.createComment(' ' + directiveName + ': '+templateAttrs[directiveName]+' ') 

如果你打電話console.log(el);你那是什麼創造了評論。如果以這種方式更改輸出,可以檢查:console.log(el [0] .parentNode)。你會看到有很多的childNodes的: enter image description here

如果您使用的指令測試之外,你會不知道這個問題的,因爲完整的創建DocumentFragment你的元素directive-name將被替換。解決這個問題的另一種方法是使用包裝元素爲你的指令模板:

<div><strong ng-repeat="foo in bar"> <p> {{ foo }} </p> </strong></div> 

在這種情況下,你可以訪問div元素。