Angular Directive Different Template

Massive Boisson picture Massive Boisson · May 10, 2013 · Viewed 25.4k times · Source

I have a directive myDirective with variable type. If I run <my-directive type="X"> I want the directive to use templateUrl: x-template.html. If I do <my-directive type="Y"> I want the directive to use templateUrl: y-template.html.

This is my current directive.

app.directive('myDirective', function() {
    var myDirective = {
        templateUrl: 'X-template.html',
        restrict: 'E',
        scope: {
            type: '=' 
        },
    };
    return myDirective;
});

I read thru stackoverflow and angular documentation but have not found anything that I need.

I am now trying to do something along the lines of:

if ($scope.type === 'X') {
    templateUrl: 'X-template.html',
}
else if ($scope.type === 'Y') {
    templateUrl: 'Y-template.html',
}

But do not know where to do it.

Do you guys know if this is possible and how?

Answer

Rob J picture Rob J · Dec 5, 2013

Angular will accept a function as the template option, so you could do something like so:

.directive('myDirective', function () {
    return {
        templateUrl: function (tElement, tAttrs) {
            if (tAttrs) {
                if (tAttrs.type === 'X') {
                    return 'X-template.html';
                }
                if (tAttrs.type === 'Y') {
                    return 'Y-template.html';
                }
            }
        }
    }
});

For more info, see the documentation for the $compile service.