rahul aggarwal rahul aggarwal - 3 months ago 36
AngularJS Question

Selecting default value in radio button angularjs

I want to show the default selected value of radiobutton as 3. My code is as follows:-

<div class="checkbox-group" ng-init="ac.ServiceCode=3">

<input type="radio" ng-model="ac.ServiceCode" id="acuOne" value="1" ng-change='GetAcuityLevel(1)'>
<label for="acuityone">1</label>

<input type="radio" ng-model="ac.ServiceCode" id="acuTwo" value="2" ng-change='GetAcuityLevel(2)'>
<label for="acuitytwo">2</label>

<input type="radio" ng-model="ac.ServiceCode" id="acuThree" value="3" ng-change='GetAcuityLevel(3)'>
<label for="acuitythree">3</label>

<input type="radio" ng-model="ac.ServiceCode" id="acuFour" value="4" ng-change='GetAcuityLevel(4)'>
<label for="acuityfour">4</label>

<input type="radio" ng-model="ac.ServiceCode" id="acuFive" value="5" ng-change='GetAcuityLevel(5)'>
<label for="acuityfive">5</label>


But in this case it always shows 3, when I remove above code it shows correct selected value in radio button. I want if service returns some value (1 to 5) then radio buttons should be selected else default value 3 should be selected.


That's because you have an ng-init that does that for you.


By this way, your default value will always be 3 and always initialized to that value.

You should handle ac.ServiceCode differently: assuming your service is an $http.get request

            success(function(data, status, headers, config) {
                 if(data.valueReturned != null)
                    $scope.ac.ServiceCode = data.valueReturned;
                    $scope.ac.ServiceCode = 3;

In other words, you should handle your default value in your service, not in your HTML.