AngularJS > Forms & Validations

Radio buttons in AngularJS

How to work with Radio buttons in AngularJS?


In the previous post, we learnt how to work with Check box. In this post, we shall learn how to work with Radio buttons in AngularJS.

In below code snppet, we declared a $scope property named "Gender" and a function named "RadioChange".

<script>

    var app = angular.module("app", []);
    app.controller("RadioController", function ($scope) {

        $scope.Gender = "Male";

        $scope.RadioChange = function (s) {
            $scope.GenderSelected = s;
        };
    });

</script>

<div ng-app="app" ng-controller="RadioController">
    Select gender
    <label><input type="radio" name="SGender" ng-change="RadioChange('Male')" ng-model="Gender" value="Male" /> Male </label>
    <label><input type="radio" name="SGender" ng-change="RadioChange('Female')" ng-model="Gender" value="Female" /> Female </label>

    <p>
        Selected gender: {{ Gender }}
    </p>
    <p>
        You have clikced on <b>{{GenderSelected}}</b>
    </p>
</div>

In the HTML block, we have two radio buttons with following

  • ng-change - function to call when the radio button value changes. This will call RadioChange function with the value as parameter
  • ng-model - directive whose value is set as "Gender" whose default value is set as "Male" in the <script> block.

In the last we have written both "Gender" and "GenderSelected" $scope proeprty on the page.

Output

Radio button in AngularJS

 Views: 51883 | Post Order: 50




Write for us






Hosting Recommendations