AngularJs: How to set radio button checked based on model
Ended up just using the built-in angular attribute ng-checked="model"
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.
One way that I see more powerful and avoid having a isDefault
in all the models is by using the ng-attributes ng-model
, ng-value
and ng-checked
.
ng-model: binds the value to your model.
ng-value: the value to pass to the ng-model
binding.
ng-checked: value or expression that is evaluated. Useful for radio-button and check-boxes.
Example of use: In the following example, I have my model and a list of languages that my site supports. To display the different languages supported and updating the model with the selecting language we can do it in this way.
<!-- Radio -->
<div ng-repeat="language in languages">
<div>
<label>
<input ng-model="site.lang"
ng-value="language"
ng-checked="(site.lang == language)"
name="localizationOptions"
type="radio">
<span> {{language}} </span>
</label>
</div>
</div>
<!-- end of Radio -->
Our model site.lang
will get a language
value whenever the expression under evaluation (site.lang == language)
is true. This will allow you to sync it with server easily since your model already has the change.
Use ng-value
instead of value
.
ng-value="true"
Version with ng-checked
is worse because of the code duplication.