动态包含模板角度指令

Dynamic include template angular directive

本文关键字:指令 包含模 动态      更新时间:2023-09-26

所以我想发出一个指令来自动包含选项卡和内容,但我无法获取存储在partials/tabs/tab[x].html中的内容。

AvailableTabs - 定义为数组的常量:

myApp.constant("availableTabs", [
    {name:'tab1', title:'One', content:'partials/tabs/tab1.html'},
    {name:'tab2', title:'Two', content:'partials/tabs/tab2.html'},
    {name:'tab3', title:'Three', content:'partials/tabs/tab3.html'}
]);

我的指令会检测要包含的正确选项卡,并尝试包含选项卡的内容:

 myApp.directive('myTabs',['availableTabs','$templateCache', function(availableTabs, $templateCache) {
        return {
            restrict: 'A',
            template: function (elem, attr) {
                for (index = 0; index < availableTabs.length; ++index) {
                    if(availableTabs[index].name == attr.myTabs) {
                        return '<tab heading="'+availableTabs[index].title+'" ng-show="1"> ' +
                                '<div ng-include="'+availableTabs[index].content+'"></div>'+
                            '</tab>';
                       //return '<tab heading="'+availableTabs[index].title+'" ng-show="1"> ' +
                       //    $templateCache.get(availableTabs[index].content)+
                       //    '</tab>';
                    }
                }
            },
    };
}]);

问题是选项卡的内容是空的,我没有错误。

我的 html 如下:

<tabset>
  <div my-tabs="tab1"></div>
  <div my-tabs="tab2"></div>
  <div my-tabs="tab3"></div>
</tabset>

我尝试在指令中注入$templateCache,但它在检索内容时返回undefined,我也尝试采用相对于脚本路径的路径,但仍然undefined

因为您在ng-include中错过了',因为将模板名称传递为 string 。因为ng-include指令需要string作为输入。

ng-include="'''+availableTabs[index].content+'''"

将呈现如下

ng-inlcude="'partials/tabs/tab1.html'"