Bootstrap – Getting Radio Buttons Value on AngularJS

junio 3, 2015

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>
  <label class="btn btn-primary">
    <input type="radio" name="options" id="option2" autocomplete="off"> Radio 2
  </label>
  <label class="btn btn-primary">
    <input type="radio" name="options" id="option3" autocomplete="off"> Radio 3
  </label>
</div>

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: option.id === form.selectedOption.id}" ng-click="form.selectedOption = option">
        <input type="radio" name="myOption" value="{{option.id}}" autocomplete="off"> {{option.label}}
    </label>
</div>

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

angular.module('myApp')
.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'}
    })

sources:
https://scotch.io/tutorials/handling-checkboxes-and-radio-buttons-in-angular-forms
https://docs.angularjs.org/api/ng/directive/ngRepeat
http://stackoverflow.com/questions/26598622/angularjs-ng-repeat-on-directive-and-parent-scope

Responder

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

Logo de WordPress.com

Estás comentando usando tu cuenta de WordPress.com. 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 )

Google+ photo

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

Conectando a %s

A %d blogueros les gusta esto: