Search code examples
javascriptangularjsreplacedirectivetransclusion

AngularJS: Modify transcluded attribute key in directive


Given:

<radio radio-name="login"></radio>

And the directive:

app.directive('radio', function () {
    return {
        restrict: 'E',
        replace: true,
        transclude: true,
        scope: {
            radioName: '@'
        },
        template: '<label></label>',
        link: function ( ... ) {}
    }
});

I want the resulting markup to be:

<label data-radio-name="login" ...>

Instead of what is currently outputted:

<label radio-name="login" ...>

I want to keep 'radio-name' on the initial markup so you can tell it is a custom directive, but I want the resulting transcluded/replaced to have the semantic data attribute 'data-radio-name'. Thanks.


Solution

  • Change radioName mode from @ to = and set template empty:

    template: '<label data-radio-name=""></label>'
    

    Something like:

    .directive('radio', function () {
        return {
            restrict: 'E',
            replace: true,
            transclude: true,
            scope: {
                radioName: '='
            },
            template: '<label data-radio-name=""></label>',
            link: function ( ) {}
        }
    });
    

    Output:

    <label data-radio-name="login"></label>
    

    Demo Fiddle