Ayush Gupta Ayush Gupta - 2 months ago 12
AngularJS Question

ng-checked Radio Button not setting ng-model value in AngularJS on page load

I am learning angularJS and was trying to use

ng-model
,
ng-checked
and
ng-if
together for radio buttons

<html>
<head>
<title>Angular JS Radio Button Test</title>
</head>
<body ng-app="">
<input type="radio" name="gender" value="M" ng-model="selectedGender" ng-checked="true"/>M<br />
<input type="radio" name="gender" value="F" ng-model="selectedGender" />F<br />
<div ng-if="selectedGender == 'M'">
Male
</div>
<div ng-if="selectedGender == 'F'">
Female
</div>

</body>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</html>


Now, on the initial page load, the "M" radio button is checked, but still the
<div ng-if="selectedGender == 'M'">
div does not show, unless I click on it again, after which it works.

What causes this issue, and how can it be fixed.

Thanks in advance.

Answer

You can initialise in "ng-init" as below.

<body ng-app="" ng-init="selectedGender = 'M'">
    <input type="radio" name="gender" value="M" ng-model="selectedGender" ng-checked="true"/>M<br />
    <input type="radio" name="gender" value="F" ng-model="selectedGender" />F<br />
    <div ng-if="selectedGender == 'M'">
        Male
    </div>
    <div ng-if="selectedGender == 'F'">
        Female
    </div>

</body>

Working plunker here.