Wednesday, December 10, 2014

AngularJS grouping radio buttons on a form

HTML input elements of radio button type are grouped together using the name attribute. With AngularJS forms (and form validation), the name attribute is generally set as a unique identifier. To get grouped radio buttons to work correctly on a form using AngularJS you simply need to set a value to each radio button.
<input type="radio" name="myGroup" value="1" ng-model="cbSelection"/> Checkbox 1
<input type="radio" name="myGroup" value="2" ng-model="cbSelection"/> Checkbox 2
// set initial value
$scope.cbSelection = '1';

// get value
var selection = $scope.cbSelection;

In the example above the two checkboxes are in the same group and share the same angular model. The active value controls which one is set to checked - although this is in textual form and not numeric.

No comments:

Post a Comment