16

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)

1 Answer 1

22

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>
Sign up to request clarification or add additional context in comments.

3 Comments

Also it will be better if you use $templateCache service to cache the template.
To handle all these details ($templateCache) automatically, just use $templateRequest.
Thanks, before i use $rootScope and it was really slow. now fixed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.