Bind ngModel to isolated scoped AngularJS directive

I am trying to create an Angular directive that displays radio inputs and 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 would like it to display 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 is 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 part. Since each directive creates an isolated scope, I'm not sure how to bind it to it.

There is a similar question here: Isolate scope but keep binding to ngModel

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

+3


source to share


1 answer


If you want to have bi-directional binding, you need to add model: '='

to your scope. This will allow you to have a model variable in your scope that will bind to the one you specify 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>

      

+3


source







All Articles