Lautaro Lautaro - 1 year ago 143
Javascript Question

Allow only one checked checkbox, Angular best practice.

Im using angular.
I have Three checkboxes in a Group and i want to make sure only one of them can be checked. So if one is checked the other two has to bee unchacked. I can Think of doing this several ways with native JS or jQuery but i want to know if there is a typical Angular way of doing it.

Here is Plunker with a set up of the checkboxes and angular controll.

<body ng-controller="MainCtrl">


<input type="checkbox" name="groupA" ng-model="vm.a1" ng-change="vm.changeGroupA()"> A1 </label>
<input type="checkbox" name="groupA" ng-model="vm.a2" ng-change="vm.changeGroupA()"> A2 </label>
<input type="checkbox" name="groupA" ng-model="vm.a3" ng-change="vm.changeGroupA()"> A3 </label>

<br> {{vm.Output}}

Answer Source

Since you can't use radio buttons, I've made this plnkr when you check one the others are deselected:

 <label> <input type="checkbox" name="groupA" ng-model="vm.a1" ng-change="vm.a2 = false; vm.a3 = false; vm.changeGroupA()" >  A1  </label> 
 <label> <input type="checkbox" name="groupA" ng-model="vm.a2" ng-change="vm.a1 = false; vm.a3 = false; vm.changeGroupA()" >  A2  </label>
 <label> <input type="checkbox" name="groupA" ng-model="vm.a3" ng-change="vm.a2 = false; vm.a1 = false; vm.changeGroupA()" >  A3  </label>

Hope it helps =)

Edit: You can probably change the state of the other checkboxes in the controller for best practice, made in the html just to demonstrate more quickly..

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download