angular load template from url and compile inside div

前端 未结 3 1943
野性不改
野性不改 2021-02-02 13:46

As I\'m new to Angular JS I was wondering how could I load an external template and compile it with some data into the targeted div.

For instance I have thi

3条回答
  •  旧时难觅i
    2021-02-02 14:19

    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. If you have a static string like in this
        // example, you might as well omit the $sce call.
        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 here
        });
    });
    

    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.

提交回复
热议问题