greengrassbluesky
greengrassbluesky

Reputation: 373

How to load Angular JS directives/templates dynamically

I want to load angular js directives dynamically.

Consider that I have 3 directives

<apple data="data"/>

apple.html will be serving the UI for apple

<banana data="data"/>

banana.html will be serving UI for banana

<mango data="data"/>

mango.html will be serving UI for mango directive

I want to load one of these directives based on my JSON data

data: { fruittype: "apple": fruitObj: {"... "}}

on UI layer

We have a JSP that will actually hold the fruit angular tags ( i.e. either <apple> , <banana> or <mango> )

My question is what to write in the JSP logic ?

Normally with the static jsp we just writing something like below;

<div ng-app="fruitApp">
<apple></apple>

</div>

Upvotes: 1

Views: 854

Answers (1)

sylwester
sylwester

Reputation: 16498

You can define function in your directive scope to get templateUrl and include template into directive template like below:

app.directive("fruit", function() {

  return {
    scope: {

      data: '=data',
      fruitType: '@type'

    },
    link: function(scope, element, attrs) {
      scope.getTemplate = function() {

        //path to yours templetes
        return scope.fruitType + '.html';
      }
    },
    template: '<div ng-include="getTemplate()"></div>',


  }


})

Full working demo you can find here http://plnkr.co/edit/VC6NfnYpcKFyhwgOot38?p=preview

Upvotes: 2

Related Questions