B G Nithin Malathesh
B G Nithin Malathesh

Reputation: 77

Handling multiple radio buttons

Here "idDefault" values are not changing. Please help me.

<div class="form-group" >
<label class="control-label">Select Colors : </label>
<div ng-repeat = "color in colorlist">
<input type="radio" name="color" ng-value="true" ng-model="color.idDefault"> 
{{color.colorName}} </input>
</div>

Colors : {{colorlist}}

and my JSON is

$scope.colorlist = [
{
  colorName:'Black',
  idDefault:true},
 {
  colorName:'Red',
  idDefault:false} ,
  { 
    colorName:'Bule',
  idDefault:false} ,
  {
  colorName:'Yellow',
  idDefault:false} ,
    ];

Initially black is selected. When selecting other colors, Black isDefault value not changing to false.

Upvotes: 2

Views: 70

Answers (2)

Viplock
Viplock

Reputation: 3319

First of all as you are using color list for radio buttons , its the way for Checkbox list . But if you wanna use it like this only , you can do it by adding a ng-change in it like -

View Code-

<div class="form-group" >
 <label class="control-label">Select Colors : </label>
 <div ng-repeat = "color in colorlist">
  <input type="radio" name="color" ng-change="changed(color)" ng- value="true" ng-model="color.idDefault"/> 
 {{color.colorName}} 
</div>
 Colors : {{colorlist}}

and in controller add a method -

$scope.changed=function(color){
for(var i=0;i<$scope.colorlist.length;i++)
if($scope.colorlist[i].colorName!==color.colorName){
$scope.colorlist[i].idDefault=false;
}
}

Check the fiddle

hope it will work for you.

Upvotes: 1

Akshay Kumar
Akshay Kumar

Reputation: 576

The method that you are trying to use above is used for checkboxes where you can select multiple value but here you want only one color to be selected at time.

You can this as,

<div class="form-group" >
<label class="control-label">Select Colors : </label>
<div ng-repeat = "color in colorlist">
   <input type="radio" name="color" ng-value="color" ng-model="selectedColor"> 
   {{color.colorName}} 
   </input>
</div>

This way you can get the selected color in your contoller in $scope.selectedColor variable.

Upvotes: 0

Related Questions