【问题标题】:Load HTML template from file into a variable in AngularJs将 HTML 模板从文件加载到 AngularJs 中的变量中
【发布时间】:2014-06-30 18:02:45
【问题描述】:

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

我不太清楚如何从文件中加载 HTML 模板并将其分配给变量。

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

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    使用$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
        });
    });
    

    请注意,这是手动执行此操作的方法,而在大多数情况下,更可取的方法是使用 definedirective 使用 templateUrl 属性获取模板。

    【讨论】:

    • 嗨,cdauth,知道如何将 JS 与平面 html 模板一起加载。
    • 非常感谢。这太棒了。
    【解决方案2】:

    所有模板都加载到缓存中。您可以使用可注入的$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 存储它们。
    • 好的 - 完美。这涵盖了我正在寻找的场景。谢谢!
    • 我的调试器告诉我它无法获得“未定义的获取”。假设我有多个博客,我想根据路由提供程序中的 ":param" 属性返回它们。这是您可以使用 $templateCache 指定的方法之一吗?
    • @dustyrockpyle 不能使用单独的文件,只有在脚本标签内有模板
    猜你喜欢
    • 2015-02-17
    • 1970-01-01
    • 2020-12-28
    • 2012-02-27
    • 2021-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-27
    相关资源
    最近更新 更多