小编典典

Angular.js 指令动态模板URL

all

routeProvider我在需要模板的模板中有一个自定义标签directive。该version属性将由范围填充,然后调用正确的模板。

<hymn ver="before-{{ week }}-{{ day }}"></hymn>

根据星期几和星期几,有多种版本的赞美诗。我期待使用该指令来填充正确的.html部分。变量没有被读取templateUrl

emanuel.directive('hymn', function() {
    var contentUrl;
    return {
        restrict: 'E',
        link: function(scope, element, attrs) {
            // concatenating the directory to the ver attr to select the correct excerpt for the day
            contentUrl = 'content/excerpts/hymn-' + attrs.ver + '.html';
        },
        // passing in contentUrl variable
        templateUrl: contentUrl
    }
});

excerpts 目录中有多个文件标记为before-1-monday.html, before-2-tuesday.html, ”


阅读 91

收藏
2022-09-02

共1个答案

小编典典

您可以使用ng-include指令。

尝试这样的事情:

emanuel.directive('hymn', function() {
   return {
       restrict: 'E',
       link: function(scope, element, attrs) {
           scope.getContentUrl = function() {
                return 'content/excerpts/hymn-' + attrs.ver + '.html';
           }
       },
       template: '<div ng-include="getContentUrl()"></div>'
   }
});

UPD。 用于观看ver属性

emanuel.directive('hymn', function() {
   return {
       restrict: 'E',
       link: function(scope, element, attrs) {
           scope.contentUrl = 'content/excerpts/hymn-' + attrs.ver + '.html';
           attrs.$observe("ver",function(v){
               scope.contentUrl = 'content/excerpts/hymn-' + v + '.html';
           });
       },
       template: '<div ng-include="contentUrl"></div>'
   }
});
2022-09-02