2014-01-19 56 views
16

编译HTML就有了下面的方式在AngularJS动态添加HTML

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

是否有可能从templateURL单独做相同或负载模板? (使用标准机制,以便将其缓存在$ templateCache中)

回答

22

当然,您只需使用$http服务来获取模板,而不是手动编译和插入它。 $http服务将隐式地处理缓存。

PLUNKER

(最简单的)指令:

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

    } 
]); 

查看:

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

指令模板(template.html):

<span>{{message}}</span> 
+0

此外,如果您使用$ templateCache服务来缓存模板会更好。 – Nilesh

+2

要自动处理所有这些细节($ templateCache),只需使用$ templateRequest。 – Interarticle

+0

谢谢,在我使用'$ rootScope'之前,它真的很慢。现在修好了。 – Miao1007