Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
747 views
in Technique[技术] by (71.8m points)

angularjs - 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.

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?

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);
        }
}

and

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...