将HTML模板从文件加载到AngularJs中的变量中

Abh*_*jar 55 angularjs

我正在使用需要将HTML绑定到富文本编辑器的表单.存储此HTML内容的最佳方式是HTML文件.

我无法弄清楚如何从文件加载HTML模板并将其分配给变量.

在使用templateUrl时,指令似乎能够做到这一点.想知道这是否有任何低级api角度来实现控制器内部相同的事情

cda*_*uth 93

使用$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
    });
});
Run Code Online (Sandbox Code Playgroud)

请注意,这是手动方式,而在大多数情况下,最好的方法是定义使用属性获取模板的指令templateUrl.


dus*_*yle 60

所有模板都加载到缓存中.您可以使用一个可注入的$ templateCache服务来访问模板:

app.controller('testCtrl', function($scope, $templateCache){
    var template = $templateCache.get('nameOfTemplate.html');
});
Run Code Online (Sandbox Code Playgroud)

  • 您是如何获取模板的?你也可以做`<script type ="text/ng-template"id ="templateId.html"src ="server/path/to/your/template.html"> </ script>`.或者您可以使用$ http服务手动获取模板并使用`$ templateCache.put`来存储它们. (5认同)