How to set radio button checked by button click in AngularJS ?
In this article, we will see how to set the radio button checked by button click in AngularJS, along with knowing its implementation through the examples.
Approach: The approach is to use the ng-checked directive to check the radio button in the DOM. In the first example, a single radio button is checked by the button and In the second example, multiple radio buttons are checked by the button. The ng-model directive is used to bind the radio buttons.
Example 1: This example illustrates setting the single radio button checked by button click in AngularJS.
<!DOCTYPE HTML>
<html>
<head>
<title>
Setting the radio button checked by
button click in AngularJS
</title>
<script src=
"//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js">
</script>
<script>
var myApp = angular.module("app", []);
myApp.controller("controller", function($scope) {
$scope.radioCh = function() {
if(!$scope.radio) {
$scope.radio = true;
} else {
$scope.radio = false;
}
}
});
</script>
<style>
body {
font-family: Arial, Helvetica, sans-serif;
text-align: center;
}
h1 {
color: green;
}
</style>
</head>
<body>
<h1>GeeksforGeeks</h1>
<h3>
How to set radio button checked
by button click in AngularJS
</h3>
<div ng-app="app">
<div ng-controller="controller"> Radio button:
<input type="radio" ng-checked="radio">
<br><br>
<button ng-click="radioCh()"
ng-model='radio'> Click here
</button>
<br><br>
</div>
</div>
</body>
</html>
Output:

Example 2: This example illustrates setting the multiple radio button checked simultaneously by button click in AngularJS.
<!DOCTYPE HTML>
<html>
<head>
<title>
Setting the radio button checked by
button click in AngularJS
</title>
<script src=
"//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js">
</script>
<script>
var myApp = angular.module("app", []);
myApp.controller("controller", function($scope) {
$scope.radioCh = function() {
if(!$scope.radio) {
$scope.radio = true;
} else {
$scope.radio = false;
}
}
});
</script>
<style>
body {
font-family: Arial, Helvetica, sans-serif;
text-align: center;
}
h1 {
color: green;
}
</style>
</head>
<body>
<h1>GeeksforGeeks</h1>
<h3>
How to set radio button checked
by button click in AngularJS
</h3>
<div ng-app="app">
<div ng-controller="controller"> Radio button 1:
<input type="radio" ng-checked="radio">
<br><br>
Radio button 2:
<input type="radio" ng-checked="radio">
<br><br>
Radio button 3:
<input type="radio" ng-checked="radio">
<br><br>
<button ng-click="radioCh()" ng-model='radio'>
Click here
</button><br>
</div>
</div>
</body>
</html>
Output:
