Dynamic include template angular directive

332 views Asked by At

So I want to make a directive to automatically include tabs and content, but I am unable to get the content stored in partials/tabs/tab[x].html.

AvailableTabs - constant defined as an array :

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

My directive detects the correct tab to be included, and tries to include the tab's content as well:

 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>';
                    }
                }
            },
    };
}]);

The problem is that the content of the tab is empty and I have no errors.

My html is the following:

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

I tried injecting $templateCache in the directive but it returns undefined when retrieving the content, I also tried to take the path relative to the script path but still undefined.

1

There are 1 answers

2
Pankaj Parkar On BEST ANSWER

Because you had missed ' in ng-include, for passing template name as string. Because ng-include directive requires string as input.

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

will be render as below

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