javascript - $digest 渲染 ng-repeat 作为注释

标签 javascript angularjs unit-testing angularjs-directive

我正在为指令编写测试,执行测试时模板(已正确加载)呈现为 <!-- 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 已正确加载
  • isolateScope 结果为 undefined

最佳答案

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

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

这些注释是由编译函数创建的——查看 Angular 源:

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

如果您调用 console.log(el);,您将获得创建的评论。如果您以这种方式更改输出,您可以检查一下:console.log(el[0].parentNode)。你会看到有很多childNodes: enter image description here

如果您在测试之外使用该指令,您将不会意识到这个问题,因为您的元素 directive-name 将被完整创建的 DocumentFragment 替换。另一种解决问题的方法是为指令模板使用包装元素:

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

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

关于javascript - $digest 渲染 ng-repeat 作为注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21478532/

相关文章:

javascript - 当另一个函数调用时,函数不会触发

javascript - 将 NGRX 添加到 Mac OS 上的 Angular 应用程序时出现 Node-gyp 重建错误

angularjs - 在AngularJS中动态更新 'max'验证

ipad - 如何在 iPad 上使用 fastClick + AngularJS

javascript - AngularJS ng-repeat 中的 if 语句条件

c++ - 单元测试应用程序到硬件的接口(interface)——模拟与否

javascript - 无法使用芯片值更新 Controller 中的模型

javascript - 更改 jquery datetimepicker 中的初始最小日期

java - 如何在 Android 单元测试中模拟 Bundle 方法?

python - pip install -U 模拟 : Error