Johnbabu Koppolu Johnbabu Koppolu - 6 months ago 92
AngularJS Question

Angular: Population of Radio button groups in loop(ng-repeat) - selection not working

I am trying to populate multiple groups of radio buttons in a loop and using a combination of group name and index for the name so as to uniquely group the radio buttons. The issue is - only the last group in the loop has the radio button checked. Other groups in the loop has nothing checked.

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example - Dynamically populate Radio buttons in a loop</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
</head>
<body ng-app="radioSetsExample">
<script>
angular.module('radioSetsExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.groups = [{
name: 'group_one',
type: 'CHOOSE'
}, {
name: 'group_two',
type: 'ADD'
},
{
name: 'group_three',
type: 'ADD'
}];
}]);
</script>
<form ng-controller="ExampleController">
<div class="radio-inline" ng-repeat="group in groups">
{{group.name}} - TYPE:
<label>
<input type="radio" name="{{group.name}}_{{$index}}" value="CHOOSE" ng-model="group.type">
Choose
</label>
<label>
<input type="radio" name="{{group.name}}_{{$index}}" value="ADD" ng-model="group.type">
Add
</label>
</div>
</form>
</body>
</html>


Plunker

Everything works fine if I manually give unique 'name' to each group in the loop and don't use index. But I cannot do that really since the list is going to be dynamic and there are no unique names. I have to depend on index to generate unique names to each group.

What am I missing here?

Answer

you can use name="{{group.name+'_'+$index}}" instead of name="{{group.name}}_{{$index}}" then should wok fine.

<form ng-controller="ExampleController">
      <div class="radio-inline" ng-repeat="group in groups">
        {{group.name}} - TYPE:
        <label>
         <input type="radio" name="{{group.name+'_'+$index}}" value="CHOOSE" ng-model="group.type">
          Choose
        </label>
        <label>
         <input type="radio" name="{{group.name+'_'+$index}}" value="ADD" ng-model="group.type">
          Add
        </label>
      </div>
 </form>
Comments