Not able to get the value of radio select setting dynamically in AngularJS

When working with radio buttons in AngularJS within loops (like ng-repeat), you need to use $index to create unique model bindings for each row. Without it, all radio buttons share the same model and interfere with each other.

Problem

Radio buttons without proper indexing share the same ng-model, causing unexpected behavior where selecting one affects others.

Solution: Using $index

Add [$index] to your ng-model to create unique bindings for each iteration:

<td><input type="radio" ng-model="classes.satisfies[$index]" value="Country1"> India</td>
<td><input type="radio" ng-model="classes.satisfies[$index]" value="Country2"> US</td>

Complete Example

<!DOCTYPE html>
<html ng-app="myApp">
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
</head>
<body ng-controller="MyController">
    <table>
        <tr ng-repeat="item in items track by $index">
            <td>{{item.name}}</td>
            <td><input type="radio" ng-model="classes.satisfies[$index]" value="India"> India</td>
            <td><input type="radio" ng-model="classes.satisfies[$index]" value="US"> US</td>
        </tr>
    </table>
    
    <h3>Selected Values:</h3>
    <div ng-repeat="selection in classes.satisfies track by $index">
        Row {{$index}}: {{selection}}
    </div>

    <script>
        angular.module('myApp', []).controller('MyController', function($scope) {
            $scope.items = [
                {name: 'Item 1'},
                {name: 'Item 2'},
                {name: 'Item 3'}
            ];
            $scope.classes = {
                satisfies: []
            };
        });
    </script>
</body>
</html>

How It Works

The $index provides a unique identifier for each iteration in ng-repeat. This creates separate model bindings like classes.satisfies[0], classes.satisfies[1], etc., allowing each row to maintain its own radio button selection independently.

Key Points

  • Always use [$index] with ng-model in repeated radio buttons
  • Each row gets its own array index for storing the selected value
  • The selected values are accessible via classes.satisfies[index]

Conclusion

Using $index with ng-model ensures radio buttons work correctly in loops by creating unique model bindings. This prevents interference between radio button groups in different rows.

Updated on: 2026-03-15T23:18:59+05:30

252 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements