2014-01-31 47 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元素。