Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Directive Different Template

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?

like image 822
Massive Boisson Avatar asked May 10 '13 20:05

Massive Boisson


People also ask

Can a directive have a template in Angular?

Components are directives with templates. The only difference between Components and the other two types of directives is the Template. Attribute and Structural Directives don't have Templates. So, we can say that the Component is a cleaner version of the Directive with a template, which is easier to use.

Can we use multiple directives in Angular?

You can not use two structural directives on the same element. You need to wrap your element in another one. It's advised to use ng-container since it wont be rendered in DOM.

Does directive have template?

The component directive is just a directive that attaches the template and style for the element, along with the specific behavior. The structural directive modifies the DOM element and its behavior by adding, changing, or removing the different elements.


2 Answers

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.

like image 116
Rob J Avatar answered Sep 30 '22 19:09

Rob J


You can work around this issue using ng-include inside compile:

app.directive('myDirective', function() {     return {         restrict: 'E',         compile: function(element, attrs) {             element.append('<div ng-include="\'' + attrs.type + '-template.html\'"></div>');         }     } }); 

fiddle

like image 22
Mark Rajcok Avatar answered Sep 30 '22 19:09

Mark Rajcok