Cris69 Cris69 - 1 year ago 154
AngularJS Question

Checkboxes like radio-buttons in Angular and Ionic

I have a list of Ionic checkboxes, if I click one I want the others to be deselected. Here is an example of the list :

<ion-checkbox ng-model="creditCard" ng-change="p_method()">
Credit Card
<ion-checkbox ng-model="cash" ng-change="p_method()">
<ion-checkbox ng-model="check" ng-change="p_method()">

In my controller I started writing something like this:

function p_method(){
$scope.creditCard = $scope.creditCard === true ? false : true;
$ = $ === true ? false : true;
$scope.check = $scope.check === true ? false : true;


I could use radio-buttons but they can’t be all deselected.

Answer Source

The easiest thing is to work with the ng-true-value and ng-false-value of the checkbox. That way you can directly bind the selected payment method to your model.


<ion-checkbox ng-repeat="(key,value) in vm.paymentTypes" ng-model="vm.paymentType" ng-true-value="'{{key}}'" ng-false-value="">{{value}}</ion-checkbox>


app.controller('MainCtrl', function($scope) {
  var vm = this;
  vm.paymentType = 'none';
  vm.paymentTypes = {
    'creditCard': 'Credit Card',
    'cash': 'Cash',
    'bankCheque': 'Bank cheque'