【问题标题】:ng-isolate-scope not being attached to templateUrlng-isolate-scope 未附加到 templateUrl
【发布时间】:2015-02-19 22:52:49
【问题描述】:

我在使用带有 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'
  }
}

下载Header.html

<p>Hello World!</p>

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

谁能解释一下这个问题?

【问题讨论】:

标签: javascript angularjs


【解决方案1】:

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

您可以在脚本标签中包含模板或使用 $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>');
  });

【讨论】:

  • 我认为您不需要将模板放入模板缓存中。我通常只使用调用 module() 函数并传入模板路径的 beforeEach():`beforeEach(module('app.directives', 'download_detail_header/views/downloadHeader.html'));尽管再三考虑,您还需要使用 karma-ng-html2js 才能使其正常工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-11
  • 2015-04-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多