Javascript $digest呈现重复作为注释

Javascript $digest呈现重复作为注释,javascript,angularjs,unit-testing,angularjs-directive,Javascript,Angularjs,Unit Testing,Angularjs Directive,我正在为一个指令编写一个测试,当执行测试时,模板(正确加载)被呈现为 首先,代码的相关部分: 测试 ... beforeEach(inject(function ($compile, $rootScope, $templateCache) { var scope = $rootScope; scope.prop = [ 'element0', 'element1', 'element2' ]; // Template loading, in the real cod

我正在为一个指令编写一个测试,当执行测试时,模板(正确加载)被呈现为

首先,代码的相关部分:

测试

...

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

...
还有一些细节:

  • 该指令在测试之外运行良好
  • 如果我将模板更改为更简单的内容,如:
    {{{bar[0]}
    测试工作正常
  • 根范围已正确加载
  • isolateScope结果为
    未定义

如果您查看angular为
ng repeat
创建的生成输出,您将在html中找到注释。例如:

<!-- ngRepeat: foo in bars  -->
如果调用
console.log(el),您会得到什么是创建的注释。如果以以下方式更改输出,则可以检查此项:console.log(el[0].parentNode)。您将看到有许多子节点:

如果在测试之外使用指令,您将不会意识到此问题,因为您的元素
指令名称
将被完整创建的
文档片段
替换。解决此问题的另一种方法是为指令模板使用包装元素:

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

在这种情况下,您可以访问
div
元素

document.createComment(' ' + directiveName + ': '+templateAttrs[directiveName]+' ')
<div><strong ng-repeat="foo in bar"> <p> {{ foo }} </p> </strong></div>