【发布时间】:2014-06-30 18:02:45
【问题描述】:
我正在处理需要将 HTML 绑定到富文本编辑器的表单。存储此 HTML 内容的最佳方式是 HTML 文件。
我不太清楚如何从文件中加载 HTML 模板并将其分配给变量。
在使用 templateUrl 时,指令似乎确实能够做到这一点。想知道这是否有任何低级 api 角度来实现控制器内部的相同功能
【问题讨论】:
标签: angularjs
我正在处理需要将 HTML 绑定到富文本编辑器的表单。存储此 HTML 内容的最佳方式是 HTML 文件。
我不太清楚如何从文件中加载 HTML 模板并将其分配给变量。
在使用 templateUrl 时,指令似乎确实能够做到这一点。想知道这是否有任何低级 api 角度来实现控制器内部的相同功能
【问题讨论】:
标签: angularjs
使用$templateRequest,您可以通过其 URL 加载模板,而无需将其嵌入到 HTML 页面中。如果模板已经加载,将从缓存中获取。
app.controller('testCtrl', function($scope, $templateRequest, $sce, $compile){
// Make sure that no bad URLs are fetched. You can omit this if your template URL is
// not dynamic.
var templateUrl = $sce.getTrustedResourceUrl('nameOfTemplate.html');
$templateRequest(templateUrl).then(function(template) {
// template is the HTML template as a string
// Let's put it into an HTML element and parse any directives and expressions
// in the code. (Note: This is just an example, modifying the DOM from within
// a controller is considered bad style.)
$compile($("#my-element").html(template).contents())($scope);
}, function() {
// An error has occurred
});
});
请注意,这是手动执行此操作的方法,而在大多数情况下,更可取的方法是使用 define 和 directive 使用 templateUrl 属性获取模板。
【讨论】:
所有模板都加载到缓存中。您可以使用可注入的$templateCache 服务来访问模板:
app.controller('testCtrl', function($scope, $templateCache){
var template = $templateCache.get('nameOfTemplate.html');
});
【讨论】:
<script type="text/ng-template" id="templateId.html" src="server/path/to/your/template.html"></script>。或者您可以使用 $http 服务手动获取模板并使用$templateCache.put 存储它们。