Let's say have have a simple template for a directive like this:
<section class="card {{width}} recipe-list-card">
<div class="card-top">
<h3>{{headerText}}</h3>
</div>
<div class="card-bottom">
<div ng-transclude></div>
</div>
</section>
In some cases I'd like to use an h2 and in others and h3. Is there a good way to change the element with a directive?
Here's what I have in my directive:
module.exports = function(app) {
app.directive('cardDirective', function() {
return {
restrict: 'AC',
replace: true,
transclude: true,
templateUrl: '/templates/card_template.html',
scope: {
header: '=',
headerText: '@',
width: '@' //two columns, three columns, etc
}
}
})
}
I'd like to assign the header variable to h2, h3 etc. So far I've only been able to get escaped html (the actual tag rendered out like <h2> in the browser).
You can create a directive for your heading tag, like this:
angular.module('myApp')
.directive('myHeading', myHeading);
function myHeading() {
return {
transclude: true,
template: function(tElement, tAttrs) {
var level = Number(tAttrs.level);
if (level < 1 || level > 6) level = 1; // default
return '<h' + level + '><ng-transclude></ng-transclude></h' + level + '>';
}
};
}
Then you could use it in your template like this:
<my-heading level="2">{{headerText}}</my-heading>
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