Using $compile on external template (templateURL) in Angular directive

前端 未结 2 1129
孤街浪徒
孤街浪徒 2020-12-13 00:15

I\'ve got a recursive Angular directive that uses a template variable and gets compiled in the link function.

Problem is, that my template has gotten re

相关标签:
2条回答
  • 2020-12-13 00:35

    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 (check the network tab to see a single network request)

    0 讨论(0)
  • 2020-12-13 00:40

    I prefer to use $http to load template if its size is bigger:-

    $http.get('mytemp.html').then(function(response) {
                element.html(response.data);
                $compile(element.contents())(scope);
                });
    
    0 讨论(0)
提交回复
热议问题