4

I want to have a tag like <h1> that I can pass the level as an attribute (for nested templates to pass the depth).

This could look like:

.directive('hx', function() {
  return {
    restrict: 'E',  transclude: true, replace: true,
    link: function(scope, element, attrs) {
        this.template = '<h' + attrs.level + ' ng-transclude></h' + scope.level + '>'
    }
  }
})

This approach does not work as expected as you can see at http://plnkr.co/edit/tt1oJySS4j0FmamEYBEr?p=preview

1
  • 1
    Please be more specific with the issue you are having. Commented Dec 22, 2017 at 15:29

1 Answer 1

2

You can set a template on a directive. Each time the link function runs, you are changing the template. The first <hx> element in your code has no template, so nothing appears. The second will use the template from the first (h1) and the third will use the template from the second (h1 again).

Instead, you want to use the transclude function for directives:

link: function(scope, element, attrs, ctrl, transclude) {
  transclude(scope, function (clone) {
    const header = angular.element('<h' + attrs.level + '></h' + attrs.level + '>');
    header.append(clone);
    element.append(header);
    // element.replaceWith(header); // variant replace=true
  });
}

This gives you access to the transcluded content in clone. Then, we create the new header element with the appropriate level, append the content (in clone) to that, and then append that header element to the hx.

http://plnkr.co/edit/ED7NU8NmZ1g3G8efQNlu?p=preview

Sign up to request clarification or add additional context in comments.

2 Comments

Almost perfect! There is just the issue that in your solution the replace: true, does not work anymore. Can that be fixed.
I figured out and added this variant above in a comment.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.