使用$对角指令外部模板(templateURL)编译 [英] Using $compile on external template (templateURL) in Angular directive
问题描述
我有一个使用模板变量,并得到了链接编译递归角指令
功能。
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).
你怎么能加载外部模板到一个指令,可以在 $编译
使用?
How can you load an external template into a directive that can be used inside the $compile
?
我见过 templateURL
,但是,这并不让我命名变量,并传递给 $编译
功能。
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)
这篇关于使用$对角指令外部模板(templateURL)编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!