Prevent angular from copying attributes when replace = true

The following directive:

var app = angular.module('demo', []);
app.directive('myDirective', function() {
    return {
        restrict: 'E',
        template: '<h1>Foo bar</h1>'
    };
});

With the following use:

<my:directive foo="bar"></my:directive>

Displays the following HTML:

<my:directive foo="bar"><h1>Foo bar</h1></my:directive>

Since I want to replace my directive with the provided template, I install replace:true. This results in the following HTML:

<h1 foo="bar">Foo bar</h1>

Note that Angular copies my directory attributes to template elements ( foo="bar"). How can I prevent this behavior?

+3
source share
1 answer

You can manually remove the attributes in the link function of the directive:

    .directive('myDirective', function() {
        return {
            restrict: 'E',
            replace: true,
            template: '<h1>Foo bar</h1>',
            link: function(scope, elm, attrs){
                elm.removeAttr('foo');
            }
        };
    });

Here's a fiddle with this directive working in your situation.

EDIT: you can extend this to dynamically remove all attributes with a simple loop:

    .directive('myDirective', function() {
        return {
            restrict: 'E',
            replace: true,
            template: '<h1>Foo bar</h1>',
            link: function(scope, elm, attrs){
                for(var attr in attrs.$attr){
                    elm.removeAttr(attr);
                }
            }
        };
    });
+2
source

All Articles