在AngularJS中动态添加HTML有如下方法
var template = '<div>{{value}}</div>';
var element = angular.element(template);
placeholder.replaceWith(element);
$compile(element)($scope);
是否可以从 templateURL 或单独加载模板执行相同的操作? (使用标准机制,使其缓存在 $templateCache 中)
最佳答案
当然,您只需使用 $http
服务来获取模板,然后手动编译和插入它。 $http
服务将隐式处理缓存。
(最简单的)指令:
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>
关于javascript - AngularJS $从 templateURL 编译 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21223961/