最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - AngularJS $compile HTML from templateURL - Stack Overflow

programmeradmin3浏览0评论

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)

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)

Share Improve this question edited Jan 20, 2014 at 0:22 webdev asked Jan 19, 2014 at 23:15 webdevwebdev 7566 silver badges17 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 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>
发布评论

评论列表(0)

  1. 暂无评论