Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angularjs 在Angular指令中对外部模板(templateURL)使用$compile_Angularjs_Templates_Angularjs Directive_External - Fatal编程技术网

Angularjs 在Angular指令中对外部模板(templateURL)使用$compile

Angularjs 在Angular指令中对外部模板(templateURL)使用$compile,angularjs,templates,angularjs-directive,external,Angularjs,Templates,Angularjs Directive,External,我有一个递归Angular指令,它使用一个模板变量,并在link函数中编译 var template = "<p>My template</p>"+ "<this-directive val='pass-value'></this-directive>"; return { scope: { ... }, ... link: function(scop

我有一个递归Angular指令,它使用一个模板变量,并在
link
函数中编译

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);
        }
}
问题是,我的模板已经变得非常长并且失去了控制,我想将其外部化到一个外部HTML文件中(这也会使自动缩进变得更容易)

如何将外部模板加载到可在
$compile
中使用的指令中

我已经看到了
templateURL
,但这不允许我命名变量并将其传递给
$compile
函数

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);
        }
}
var模板=
“我的模板

”+ ""; 返回{ 范围:{ ... }, ... 链接:功能(范围、元素){ html(模板); $compile(element.contents())(范围); } }

如果模板的大小更大,我更喜欢使用$http加载模板:-

$http.get('mytemp.html').then(function(response) {
            element.html(response.data);
            $compile(element.contents())(scope);
            });

您可以使用
$templaterrequest
服务获取模板。这是一项方便的服务,它还将模板缓存在
$templateCache
中,这样只需向
template.html
发出一个请求

作为说明(不涉及递归指令的问题),如下所示:

link: function(scope, element){
   $templateRequest("template.html").then(function(html){
      var template = angular.element(html);
      element.append(template);
      $compile(template)(scope);
   });
};

(查看网络选项卡以查看单个网络请求)

这太棒了!你是我的英雄!我能给你买杯咖啡吗?我很好奇,在你的插图中的“template.html”里面可以使用html绑定(ng bind html)吗?我不能让它工作。@zhekaus,是的,但是你仍然需要使用通常的
ngSanitize
/
$sanitize
或者使用
$sce.trustAsHtml
你知道为什么在转换为字符串或控制台日志时会显示为不可编译吗?奇怪的是,有没有一种方法可以维护模板的双向绑定。htmly你应该缓存你需要的模板加载,如下所示:
$http.get('mytem.html',{cache:$templateCache})。然后(函数(response){element.html(response.data);$compile(element.contents())(scope);})
代码中缺少括号,但我无法编辑,因为它少于6个字符:)$templateRequest服务运行安全检查,然后使用$http下载提供的模板,成功后,将内容存储在$templateCache中。因此,
$templateCache
使用
$http
在一行中执行附加操作。我看到的唯一区别是模板没有放入
$templateCache
,这是您代码的目的吗?