Bootstrap – Getting Radio Buttons Value on AngularJS

To create a group of buttons that act like a radio group or checkbox group you can use the example provided on Bootstrap’s documentation

<div class="btn-group" data-toggle="buttons">
  <label class="btn btn-primary active">
    <input type="radio" name="options" id="option1" autocomplete="off" checked> Radio 1 (preselected)
  <label class="btn btn-primary">
    <input type="radio" name="options" id="option2" autocomplete="off"> Radio 2
  <label class="btn btn-primary">
    <input type="radio" name="options" id="option3" autocomplete="off"> Radio 3

Now, if you want to use that code with angular ng-repeat directive, you could do it like this

<div class="btn-group" data-toggle="buttons">
    <label ng-repeat="option in options" class="btn btn-default"
           ng-class="{active: ===}" ng-click="form.selectedOption = option">
        <input type="radio" name="myOption" value="{{}}" autocomplete="off"> {{option.label}}

Things to notice

  • Since ng-repeat creates a new scope we should use an object to store the selected value, form in this case.
  • We used an ng-class directive to preselect a value based on our model.
  • We used an ng-click directive to update our model instead of an ng-model directive, ng-modeldidn’t work for me, I suppose that it’s because radio buttons evaluate to true or false but I’m not sure.
  • We used the attribute autocomplete="off" to avoid problems with mozilla firefox

Finally, here is the model

.controller('myController', function($scope){
        $scope.options = [{id: 'F', label: 'Fruit'},
            {id: 'V', label: 'Vegetables'},
            {id: 'G', label: 'Grains'}
            {id: 'D', label: 'Dairy'}]
        $scope.form.selectedOption = {id: 'V'}




Introduce tus datos o haz clic en un icono para iniciar sesión:

Logo de

Estás comentando usando tu cuenta de Cerrar sesión /  Cambiar )

Google photo

Estás comentando usando tu cuenta de Google. Cerrar sesión /  Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Cerrar sesión /  Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Cerrar sesión /  Cambiar )

Conectando a %s