AngularJS directive, which sets a custom tag name to a specific string

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

It might look like this:

.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 properly, as you can see at http://plnkr.co/edit/tt1oJySS4j0FmamEYBEr?p=preview

+4
source share
1 answer

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

transclude :

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
  });
}

clone. , ( clone), hx.

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

+2

Source: https://habr.com/ru/post/1691238/


All Articles