在 Angular 指令中对外部模板 (templateURL) 使用 $compile [英] Using $compile on external template (templateURL) in Angular directive
问题描述
我有一个递归 Angular 指令,它使用模板变量并在 link
函数中编译.
I've got a recursive Angular directive that uses a template variable and gets compiled in the link
function.
问题是,我的模板变得很长而且失控,我想将它外部化到一个外部 HTML 文件中(这也可以让自动缩进更容易).
Problem is, that my template has gotten really long and out of control and I want to externalize it in an external HTML file (it would also make it easier for example to auto-indent).
如何将外部模板加载到可以在 $compile
内部使用的指令中?
How can you load an external template into a directive that can be used inside the $compile
?
我见过 templateURL
,但这并不能让我命名变量并将其传递给 $compile
函数.
I've seen templateURL
, but that doesn't let me name the variable and pass it to the $compile
function.
var template =
"<p>My template</p>"+
"<this-directive val='pass-value'></this-directive>";
return {
scope: {
...
},
...
link: function(scope, element){
element.html(template);
$compile(element.contents())(scope);
}
}
和
推荐答案
您可以使用 $templateRequest
服务来获取模板.这是一项便利的服务,它也将模板缓存在 $templateCache
中,以便只对 template.html
发出单个请求.
You can use the $templateRequest
service to get the template. This is a convenience service that also caches the template in $templateCache
, so that only a single request to template.html
is made.
作为说明(并且不涉及递归指令的问题),它的用法如下:
As an illustration (and without going into the issue of recursive directives), this is used like so:
link: function(scope, element){
$templateRequest("template.html").then(function(html){
var template = angular.element(html);
element.append(template);
$compile(template)(scope);
});
};
plunker(检查网络选项卡以查看单个网络请求)
plunker (check the network tab to see a single network request)
这篇关于在 Angular 指令中对外部模板 (templateURL) 使用 $compile的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!