Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS $compile HTML from templateURL

There is the following way to add HTML dynamically in AngularJS

   var template = '<div>{{value}}</div>';
   var element = angular.element(template);
   placeholder.replaceWith(element);
   $compile(element)($scope);

Is it possible to do the same from templateURL or load template separately? (with standard mechanism so that it is cached in $templateCache)

like image 450
webdev Avatar asked Jan 19 '14 23:01

webdev


People also ask

What does $compile do in AngularJS?

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.

What is Prelink and Postlink in AngularJS?

Pre-linking function Executed before the child elements are linked. Not safe to do DOM transformation since the compiler linking function will fail to locate the correct elements for linking. Post-linking function Executed after the child elements are linked.

What is BindToController in AngularJS?

Angular introduces a new property to the directive definition object called bindToController. BindToController enables the inherited properties to be bound to the Controller without $scope object.

What is the difference between link and compile in AngularJS?

Link function: It is used for registering DOM listeners as well as instance DOM manipulation. It is executed once the template has been cloned. Compile: traverse the DOM and collect all of the directives.


1 Answers

Sure, you simply use $http service to fetch the template and than compile and insert it manually. $http service will take care of caching implicitly.

PLUNKER

(Simplest) directive:

app.directive('message', [
  '$http',
  '$compile',
  function($http, $compile) {
    var tpl = "template.html";

    return {
      scope: true,
      link: function(scope, element, attrs){
        scope.message = attrs.message;

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

  }
]);

View:

<span message="Hi World!"></span>
<span message="My name is Angular."></span>

Directive template (template.html):

<span>{{message}}</span>
like image 111
Stewie Avatar answered Sep 19 '22 06:09

Stewie