Load HTML template from file into a variable in AngularJs

前端 未结 2 1231
后悔当初
后悔当初 2020-12-12 18:27

I\'m working with a form that needs to bind HTML to a Rich Text Editor. The best way to store this HTML content would be an HTML file.

I can\'t quite figure out how

相关标签:
2条回答
  • 2020-12-12 18:33

    Using $templateRequest, you can load a template by it’s URL without having to embed it into your HTML page. If the template is already loaded, it will be taken from the cache.

    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
        });
    });
    

    Be aware that this is the manual way to do it, and whereas in most cases the preferable way would be to define a directive that fetches the template using the templateUrl property.

    0 讨论(0)
  • 2020-12-12 18:37

    All templates are loaded into a cache. There is an injectable $templateCache service you can use to get access to the templates:

    app.controller('testCtrl', function($scope, $templateCache){
        var template = $templateCache.get('nameOfTemplate.html');
    });
    
    0 讨论(0)
提交回复
热议问题