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?
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With