In this article I will explain with an example, how to get checked (selected) value of RadioButton from a list of RadioButtons populated using ng-repeat directive in AngularJS.
This article will explain how to populate multiple RadioButtons using ng-repeat directive and get its checked (selected) value in Controller on Button click.
AngularJS ng-repeat RadioButton checked: Get checked (selected) value of RadioButton in AngularJS ng-repeat
The below HTML Markup consists of an HTML DIV to which ng-app and ng-controller AngularJS directives have been assigned.
The AngularJS app HTML DIV consists of another HTML DIV with a RadioButton and Label elements. The ng-repeat directive has been applied to the HTML DIV in order to populate RadioButtonList i.e. List of multiple RadioButtons from a JSON array.
The value attribute of the RadioButton has been assigned the FruitId property.
The ng-model attribute of the RadioButton has been assigned the SelectedFruitId Model variable. Thus whenever a RadioButton is selected, the SelectedFruitId Model variable will contain the value of the selected RadioButton.
Note: The SelectedFruitId Model variable is accessed using $parent scope as ng-repeat creates its own $scope.
The Button has been assigned ng-click directive. When the Button is clicked, the GetValue function of the Controller gets called.
Inside the function, a loop is executed over the JSON array and the value of the selected RadioButton i.e. the FruitId is fetched from the SelectedFruitId Model variable.
The FruitId value is used to fetch the Name property from the JSON array.
Finally the Fruit Id and Name of the selected RadioButton is displayed using JavaScript Alert Message Box.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('MyApp', [])
app.controller('MyController', function ($scope, $window) {
$scope.Fruits = [{
FruitId: 1,
Name: 'Apple'
}, {
FruitId: 2,
Name: 'Mango'
}, {
FruitId: 3,
Name: 'Orange'
}];
$scope.GetValue = function () {
var fruitId = $scope.SelectedFruitId;
var fruitName;
for (var i = 0; i < $scope.Fruits.length; i++) {
if ($scope.Fruits[i].FruitId == fruitId) {
fruitName = $scope.Fruits[i].Name;
break;
}
}
var message = "Value: " + fruitId + " Text: " + fruitName + "\n";
$window.alert(message);
}
});
</script>
<div ng-app="MyApp" ng-controller="MyController">
<div ng-repeat="fruit in Fruits">
<label for="rbCustomer_{{fruit.FruitId}}">
<input id="rbCustomer_{{fruit.FruitId}}" type="radio" ng-model="$parent.SelectedFruitId"
value="{{fruit.FruitId}}" />
{{fruit.Name}}
</label>
</div>
<br />
<br />
<input type="button" value="Get" ng-click="GetValue()" />
</div>
</body>
</html>
Screenshot
Demo
Downloads