javascript - ng-isolate-scope 未附加到 templateUrl

标签 javascript angularjs

我在使用 templateUrl 的隔离范围时遇到问题。

我的指令测试:

beforeEach(ngModule('app.directives'));
  var scope, compile
  beforeEach(inject(function($rootScope, $compile){
    scope = $rootScope.$new();
    compile = $compile;
  }));

  it('Replaces the element with the appropriate content', function(){
    var element = compile('<download-detail-header></download-detail-header>')(scope);
    expect(element.html()).to.equal('<p>Hello World!</p>');
  });

我的指令:

function downloadDetailHeader() {
  return {
    restrict: 'EA',
    scope: {},
    template: '<p>Hello World!</p>'
    // templateUrl: 'download_detail_header/views/downloadHeader.html'
  }
}

下载标题.html

<p>Hello World!</p>

测试通过模板,似乎是因为 ng-isolate-scope 被添加到指令元素上的类中。使用提供的 templateUrl 测试未通过,并且指令元素上未放置 ng-isolate-scope。

有人能解释一下这个问题吗?

最佳答案

@Claies 评论是正确的。当您在指令中引用模板文件时,Angular 必须获取它。它将编译和链接推迟到加载模板之后。您的测试正在评估获取模板之前的结果。

您可以在脚本标记中包含模板,或者在运行测试之前使用 $templateCache.put() 方法手动将模板放入缓存中。

beforeEach(ngModule('app.directives'));
  var scope, compile
  beforeEach(inject(function($rootScope, $compile, $templateCache){
    scope = $rootScope.$new();
    compile = $compile;
    $templateCache.put('downloadHeader.html', '<p>Hello World!</p>');
  }));

  it('Replaces the element with the appropriate content', function(){
    var element = compile('<download-detail-header></download-detail-header>')(scope);
    expect(element.html()).to.equal('<p>Hello World!</p>');
  });

关于javascript - ng-isolate-scope 未附加到 templateUrl,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28618570/

相关文章:

javascript - HTML5 FileReader 无法触发函数

javascript - 如何在 Angular js 中从数组中获取数据

javascript - 为 Angular Material 配置深色主题

javascript - 如何在同一页面上运行两个相同的联合脚本?

javascript - 当表单与ajax提交事件一起使用时,为什么通常使用<form>而不是<div>来聚合元素?

javascript - 将 $scope 变量传递到带 Angular html 函数标记中

javascript - 调整 Angular Material 中的圆形进度

python - Web 抓取 - 如何通过 Angular.js 访问以 JavaScript 呈现的内容?

javascript - 当在 HTML 主体末尾引用外部 JavaScript 文件时,如何调用 JavaScript 函数?

javascript - ajax成功时过滤json的Key值