Search code examples
javascriptangularjs

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. http://plnkr.co/edit/IZmGwktrCaYNyrWjfSqf?p=preview

<body ng-controller="MainCtrl">

  <div>
    {{vm.Output}}

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

    <br>
    <br>
    <br> {{vm.Output}}
</body>


Solution

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

    http://plnkr.co/edit/apSE3cIXA7DIvulBfNGX?p=preview

     <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..