简体   繁体   中英

AngularJS radio button selected value not working

Hi I am developing web application in Angularjs and web html. I have two radio buttons for male and female. I want to set male as checked by default. I tried many ways but it is not working. Finally i tried with ng-checked="True" and it worked. But when i check male i am getting undefined in angular code.

<label for="male" class="male">
                                {{ 'Male' | translate }}
                                <span class="input-icon"><img src="images/male-icon.png"></span>
                                <input type="radio" id="male" name="selector" ng-model="Gender" value="M" ng-checked="true">
                                <span class="selector-male"></span>
                            </label>
                            <label for="female" class="female">
                                {{ 'Female' | translate }}
                                <span class="input-icon"><img src="images/female-icon.png"></span>
                                <input type="radio" id="female" name="selector" ng-model="Gender" value="F">
                                <span class="selector-female"></span>
                            </label>

Above code selects male by default. But problem is when i select female i am getting female in below code.

  Gender: $scope.Gender

Whenever i dont select anything(By default male will be clicked) i am getting undefined in Gender: $scope.Gender. May i know the reason why i am getting undefined? Any help would be appreciated. Thank you

The problem is:

ng-checked=true will set the checkbox only as true and not the currentValue in question. To fix, you should:

ng-checked="Gender" in HTML and $scope.Gender = 'M' in your controller.

If you don't want to add anothing in controller, wrap the code in a div as:

<div ng-init="Gender='M'"><label></label></div>

Plunkr: https://plnkr.co/edit/i4WK990a8zHyYkoW8pIb?p=preview

删除名称属性和ng-checked然后它工作正常。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM