Marksmanship Marksmanship - 2 years ago 106
AngularJS Question

Getting the Value of Radio Button

Edit:
I am getting

undefined
when I tried to submit the
ng-model
of the
radio
.
Sample code in my
submit button
:

ng-click="addSubscriber(plan)"


Tried to
console.log(plan)
inside the
addSubscriber()
but getting
undefined
.




I am having headache because of the problem of getting the selected value of radio button. The value is showing and it is rendering
radio
depends on my
data
. But
ng-model
doesn't work, I can't get the value of selected
radio
.

<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div ng-repeat="plan in plans" class="radio">
<label><input type="radio" ng-model="plan.plan" value="{{plan.plan_code}}" name="plan.plan_name">{{plan.plan_name | capitalize}}
</label>
</div>
</div>
<pre>{{plan.plan}}</pre>
</div>


No value is showing in
<pre>
tag. I searched and tried some posted answers in other topics but its not working.

Answer Source

Update:

Another problem was that the ng-model inside the ng-repeat was unable to update the controller variable, this is due to that fact that.

ng-repeat directive creates a new scope.

Thus we need to change the ng-model from chosenPlan to $parent.chosenPlan, which will update the parent scope instead.

In the above scenario, the input radio buttons need to be set under a common name for them to act as group of radio buttons. The value of the radio button also needs to be set to a common variable which can be used in the submit function.

<label>
    <input type="radio" ng-model="$parent.chosenPlan" ng-value="plan.plan_code" name="test"/>
        {{plan.plan_name | capitalize}}
</label>

In the above form we can see that the ng-model is set to a common variable. The group name name attribute is set to a common name.

Please find below a working model of the same.

JSFiddle Demo

Old Answer:

The <pre> tag lies outside the ng-repeat move it inside, change the value to ng-value as shown below. Name for it to have the proper value should be name="{{plan.plan_name}}". Let me know if you face any issues.

<div ng-controller='MyController'>
  <div class="row">
    <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
      <div ng-repeat="plan in plans" class="radio">
        <label>
        <input type="radio" ng-model="plan.plan" ng-value="plan.plan_code" name="{{plan.plan_name}}"/>{{plan.plan_name | capitalize}}
        </label>
        <pre>{{plan.plan}}</pre>
      </div>
    </div>
  </div>
</div>

Mocked up the data and providing an example for reference:

JSFiddle Demo

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download