Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript AngularJS$从templateURL编译HTML_Javascript_Angularjs_Angularjs Directive - Fatal编程技术网

Javascript AngularJS$从templateURL编译HTML

Javascript AngularJS$从templateURL编译HTML,javascript,angularjs,angularjs-directive,Javascript,Angularjs,Angularjs Directive,有以下方法可以在AngularJS中动态添加HTML var template = '<div>{{value}}</div>'; var element = angular.element(template); placeholder.replaceWith(element); $compile(element)($scope); var模板=“{{value}}”; var元素=角度元素(模板); 占位符.替换为(元素); $compile(

有以下方法可以在AngularJS中动态添加HTML

   var template = '<div>{{value}}</div>';
   var element = angular.element(template);
   placeholder.replaceWith(element);
   $compile(element)($scope);
var模板=“{{value}}”;
var元素=角度元素(模板);
占位符.替换为(元素);
$compile(元素)($scope);

是否可以从templateURL或单独加载模板执行相同操作?(使用标准机制,将其缓存在$templateCache中)

当然,您只需使用
$http
服务获取模板,然后手动编译并插入即可
$http
服务将隐式地处理缓存

(最简单的)指令:

app.directive('message'[
“$http”,
“$compile”,
函数($http,$compile){
var tpl=“template.html”;
返回{
范围:正确,
链接:函数(范围、元素、属性){
scope.message=attrs.message;
$http.get(tpl)
.然后(功能(响应){
html($compile(response.data)(scope));
});
}
};
}
]);
视图:


指令模板(
template.html
):

{{message}

如果您使用$templateCache服务来缓存模板,也会更好。要自动处理所有这些细节($templateCache),只需使用$templateRequest。谢谢,在我使用
$rootScope
之前,它真的很慢。现在修好了。