Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically change html element in Angular directive

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).

like image 435
Kenji Crosland Avatar asked May 05 '26 23:05

Kenji Crosland


1 Answers

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>
like image 179
Shaun Scovil Avatar answered May 08 '26 13:05

Shaun Scovil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!