Heather Heather - 1 year ago 272
AngularJS Question

AngularJS Radiobutton Selected on Page Load

I am creating a list via API call. I need the first radio button in that list to be selected. If there is a case where there is only one item in the list I want that item to be automatically selected and then directed to the next page.
The below code only visually selects the radio button - does not reflect the value unless it is clicked.

<tr ng-repeat="i in app | filter:searchApp">
<td class="text-center">
<input type="radio" ng-model="$parent.currentApp" id={{i.name}} value="{{i.id}}"
ng-click="getVal(i)" name="radio" ng-checked="$first">
<label class="ui-radio" for={{i.name}}></label>

$(function() {
var $radios = $('input:radio[name=radio]');
if($radios.is(':checked') === false) {
$radios.filter('[value=i.id]').prop('checked', true);
$rootScope.app= i.id;

I get an error with this JQuery as it does not recognize the value=i.id.
Please help me have the radio button selected on page load, so that the value is selected(not just visually checked). The solution can be AngularJS or Jquery.

Thanks for your help.

Answer Source

You can achieve the desired result using pure angular. Here's the working DEMO I created.

Summary: Create a model $scope.selectedListItem = null; When you get the data from server, (in my case $scope.apiDataList is the data) , do this to select the first radio button:

//for multiple elements/options
$scope.apiDataList = [{id:1,name:"male"},{id:2,name:"female"}];

//now when you have got the data, select the first element
$scope.selectedListItem = $scope.apiDataList[0];

Now you have the actual value of the first radio button selected, we want to show it visually now. Use something similar in your code as below :

<input type="radio" ng-model="selectedListItem" id={{item.name}} value="{{item.id}}"
                     ng-click="selectRadioButton(item)" name="radio" ng-checked="selectedListItem==item">

Notice the ng-checked="selectedListItem==item" snippet. That is what marks the radio button checked visually if the current radio button is the selected one. When you need to use the value of selected list-item/radio button later on, use $scope.selectedListItem.

Hope this helps