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!