3

I'm trying to build an Angular directive that renders radio inputs and the associated labels. The HTML for the directive looks like this:

<d-radio name="gender" value="male" label="I'm a male"></d-radio>
<d-radio name="gender" value="female" label="I'm a female"></d-radio>

I'd like it render the equivalent of this:

<input type="radio" name="gender" id="male" value="male" ng-model="gender"><label for="male">I'm a male</label>
<input type="radio" name="gender" id="female" value="female" ng-model="gender"><label for="female">I'm a female</label>

And here's the JS code:

app.directive('dRadio', function() {
    return {
        restrict: 'E',
        scope: true,
        template: '<input type="radio" id="{{value}}" name="{{name}}" value="{{value}}"><label for="{{value}}">{{label}}</label>',
        link: function(scope, element, attrs) {
            scope.name = attrs.name;
            scope.value = attrs.value;
            scope.label = attrs.label;
        }
    };
});

The only thing missing from my directive is the ng-model portion. Since each directive creates an isolated scope, I'm not sure how to bind the model to it.

There is a similar Stack Overflow question here: Isolating directive scope but preserve binding on ngModel

I tried this solution, but I couldn't get it to work. Any ideas? Thanks!

Community
  • 1
  • 1
Rodney
  • 125
  • 1
  • 7

1 Answers1

3

If you want to have a bi-directional binding you will need to add an model: '=' to your scope. That will allow you to have a model variable in your scope which will be binded with the one you indicate in the html

app.directive('dRadio', function() {
    return {
        restrict: 'E',
        scope: { model: '=' },
        template: '<input type="radio" ng-model="{{model}}" id="{{value}}" name="{{name}}" value="{{value}}">    <label for="{{value}}">{{label}}</label>',
        link: function(scope, element, attrs) {
            scope.name = attrs.name;
            scope.value = attrs.value;
            scope.label = attrs.label;
        }
    };
});

And in your html

<d-radio name="gender" value="male" label="I'm a male" model="gender"></d-radio>
Adlen Afane
  • 1,422
  • 14
  • 24