Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 924
CodyBugstein Avatar asked Mar 04 '15 12:03

CodyBugstein


People also ask

What does $compile do in AngularJS?

Overview. Compiles an HTML string or DOM into a template and produces a template function, which can then be used to link scope and the template together. The compilation is a process of walking the DOM tree and matching DOM elements to directives. Note: This document is an in-depth reference of all directive options.

What is restrict option in directive?

Note: When you create a directive, it is restricted to attribute and elements only by default. In order to create directives that are triggered by class name, you need to use the restrict option. The restrict option is typically set to: 'A' - only matches attribute name. 'E' - only matches element name.


2 Answers

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)

like image 148
New Dev Avatar answered Sep 30 '22 19:09

New Dev


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);             }); 
like image 25
squiroid Avatar answered Sep 30 '22 20:09

squiroid