我在使用 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/