【问题标题】:Using $compile on external template (templateURL) in Angular directive在 Angular 指令中对外部模板 (templateURL) 使用 $compile
【发布时间】:2015-05-05 10:22:33
【问题描述】:

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

问题是,我的模板已经变得很长并且无法控制,我想将它外部化到一个外部 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);
        }
}

【问题讨论】:

    标签: angularjs templates angularjs-directive external


    【解决方案1】:

    您可以使用$templateRequest 服务来获取模板。这是一项便利服务,它还将模板缓存在$templateCache 中,因此只向template.html 发出单个请求。

    作为说明(并且不涉及递归指令的问题),它的用法如下:

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

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

    【讨论】:

    • 这太棒了!你是我的英雄!我可以请你喝杯咖啡吗?
    • 我很好奇,是否可以在插图中的“template.html”中使用 html 绑定(ng-bind-html)?我不能让它工作。
    • @zhekaus,是的,但是您仍然需要使用通常的ngSanitize/$sanitize 或使用$sce.trustAsHtml
    • 你知道为什么当它被转换为字符串或控制台记录时,它似乎无法编译吗?
    • 只是好奇有没有办法为 template.html 维护双向绑定
    【解决方案2】:

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

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

    【讨论】:

    • 你应该缓存你加载的模板,像这样$http.get('mytem.html', {cache: $templateCache}).then(function(response) { element.html(response.data); $compile(element.contents())(scope); })
    • 代码中缺少括号,但我无法编辑,因为它少于 6 个字符 :)
    • “$templateRequest 服务运行安全检查,然后使用 $http 下载提供的模板,并在成功后将内容存储在 $templateCache 中。” AngularJS 所以@ 987654324@ 使用$http 在一行中执行附加操作。我看到的唯一区别是模板没有放入$templateCache,这是你代码的目的吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-11
    • 2017-10-28
    • 2015-01-16
    • 1970-01-01
    • 2020-03-09
    • 2017-05-20
    相关资源
    最近更新 更多