4

i am trying to create a generic radioButton directive which will take options from controller for display:

<cs-radio-field options="gender" ng-model="genderValue"></cs-radio-field> 

and the options would be like

$scope.gender = { label: "Gender", required:true, valueList: [{ text: "Male", value: "yes" },{text:"Female", value:"no"}] }; 

the directive is defined as:

app.directive("csRadioField", function () { var templateHtml = function () { return '<div ng-form="myform">' + '<div class="control-group" class="{{options.class}}">' + '<div class="control-label">{{options.label || "Radio"}} {{ options.required ? "*" : ""}} </div>' + '<div class="controls">' + '<div class="radio" ng-repeat="(key, option) in options.valueList">' + '<label> <input type="radio" name="myfield" ng-value="option.value" ng-model="ngModel" ng-required="options.required" />{{option.text}} </label>' + '</div>' + '<div class="field-validation-error" data-ng-show="myform.myfield.$invalid && myform.myfield.$dirty"> ' + '<div data-ng-show="myform.myfield.$error.required">{{options.label}} is required!!!</div>' + '</div>' + '</div>' + '</div>' + '</div>'; }; return { scope: { options: '=', ngModel: '=' }, required: ['ngModel', '^form'], restrict: 'E', template: templateHtml, }; }); 

but the ngModel is not binding in the parent scope.. mostly because of new scopes being created by ng-repeat.

how to solve this issue?

the plunker link: http://plnkr.co/edit/myS5hXwxjoDEqQI2q5Q7?p=preview

1 Answer 1

8

Try this in your template:

ng-model="$parent.ngModel" 

DEMO

You're correct that ng-repeat creates child scopes. You're actually binding to child scopes' property.

Sign up to request clarification or add additional context in comments.

2 Comments

perfect, its working.. and i understand that its assigning to parent scope... but in case i use this directive inside other directives - will that create a problem??
@HarishR: there should be no problem, the $parent here is your current directive's scope.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.