Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS directive dynamic templates

I'm trying to make directive with differtent templates based on scope value.

This is what i done so far which i don't know why doesn't work http://jsbin.com/mibeyotu/1/edit

HTML element:

<data-type content-attr="test1"></data-type>

Directive:

var app = angular.module('myApp', []);

app.directive('dataType', function ($compile) {

    var testTemplate1 = '<h1>Test1</h1>';
    var testTemplate2 = '<h1>Test2</h1>';
    var testTemplate3 = '<h1>Test3</h1>';

    var getTemplate = function(contentType){

        var template = '';

        switch(contentType){
            case 'test1':
                template = testTemplate1;
                break;
            case 'test2':
                template = testTemplate2;
                break;
            case 'test3':
                template = testTemplate3;
                break;
        }

        return template;
    }; 

    var linker = function(scope, element, attrs){
        element.html(getTemplate(scope.content)).show();
        $compile(element.contents())(scope);
    };

    return {
        restrict: "E",
        replace: true,
        link: linker,
        scope: {
            content:'='
        }
    };
});
like image 402
Jack Avatar asked Apr 14 '14 16:04

Jack


2 Answers

You can set the template property of your directive definition object to a function that will return your dynamic template:

restrict: "E",
replace: true,
template: function(tElement, tAttrs) {
    return getTemplate(tAttrs.content);
}

Notice that you don't have access to scope at this point, but you can access the attributes through tAttrs.

Now your template is being determined before the compile phase, and you don't need to manually compile it.

like image 75
DRiFTy Avatar answered Oct 14 '22 11:10

DRiFTy


You can also do it very straightforward like this:

appDirectives.directive('contextualMenu', function($state) {
    return {
      restrict: 'E',
      replace: true,
      templateUrl: function(){
        var tpl = $state.current.name;
        return '/app/templates/contextual-menu/'+tpl+'.html';
      }
    };
});
like image 26
eloone Avatar answered Oct 14 '22 09:10

eloone