简体   繁体   中英

AngularJS transclude HTML attributes inside directive

I have a directive:

.directive("radio", function () {
        return {
            restrict: "EA",
            replace: true,
            scope: { text: "@", name: "@", value: "&" },
            template: '<label class="radio" for="{{name}}">\
                    <span class="icons">\
                        <span class="first-icon fui-radio-unchecked"></span>\
                        <span class="second-icon fui-radio-checked"></span>\
                    </span>\
                    <input type="radio" id="{{name}}" name="{{name}}" value="{{value}}" ng-model="value" />\
                    <span ng-bind="text"></span>\
                </label>',
            link: function (scope, el) {
                scope.value = false;
                scope.$watch("value", function (value) {
                    value ? el.addClass("checked") : el.removeClass("checked");
                });
            }
        };
    })

Right now I use it like:

<radio name="test" value="testvalue"></radio>

I don't like having to add scope variables everytime I want to add something, it would be nice if I could do:

<radio id="{{name}}" name="{{name}}" value="{{value}}" ng-model="value" required></radio>

And have the resulting HTML would be:

<label class="radio" for="{{name}}">
    <span class="icons">
        <span class="first-icon fui-radio-unchecked"></span>
        <span class="second-icon fui-radio-checked"></span>
    </span>
    <input type="radio" id="{{name}}" name="{{name}}" value="{{value}}" ng-model="value" required />
        <span ng-bind="text"></span>
</label>

The link function has an attrs variable that represents the attributes in the directive tag. You can work with that and insert data into necessary tags. But you won't be able to nicely do 2way binding without scope variables

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM