Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJs: How to set radio button checked based on model

I have a model returning in the storeLocations object with a isDefault value. if isDefault returns true, I wan't to set that radio button in the group as checked.

Not sure if I need to do a $each(data, function(index,value) and iterate through each object returned or if there's an easier way to do this using angular constructs.

Object:

storeLocations = [  {   ... more values,   isDefault: true  } ] 

Markup:

    <tr ng-repeat="location in merchant.storeLocations">         <td>{{location.name}}</td>         <td>{{location.address.address1}}</td>         <td>{{location.address.address2}}</td>         <td>{{location.address.city}}</td>         <td>{{location.address.stateProvince}}</td>         <td>{{location.address.postalCode}}</td>         <td>{{location.address.country}}</td>         <td>{{location.website}}</td>         <td>{{location.zone}}</td>         <td><input type="radio" ng-model="location.isDefault" value="{{location.isDefault}}" name="isDefault_group"></td> 
like image 685
Christopher Marshall Avatar asked Jan 25 '13 21:01

Christopher Marshall


2 Answers

Use ng-value instead of value.

ng-value="true" 

Version with ng-checked is worse because of the code duplication.

like image 136
ivan.a.bovin Avatar answered Sep 19 '22 13:09

ivan.a.bovin


If you have a group of radio button and you want to set radio button checked based on model, then radio button which has same value and ng-model, is checked automatically.

<input type="radio" value="1" ng-model="myRating" name="rating" class="radio"> <input type="radio" value="2" ng-model="myRating" name="rating" class="radio"> <input type="radio" value="3" ng-model="myRating" name="rating" class="radio"> <input type="radio" value="4" ng-model="myRating" name="rating" class="radio"> 

If the value of myRating is "2" then second radio button is selected.

like image 44
Rubi saini Avatar answered Sep 19 '22 13:09

Rubi saini