Cris69 Cris69 - 5 months ago 80
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>
<ion-checkbox ng-model="cash" ng-change="p_method()">
Cash
</ion-checkbox>
<ion-checkbox ng-model="check" ng-change="p_method()">
Check
</ion-checkbox>


In my controller I started writing something like this:

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


EDIT:

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

Answer

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.

View

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

Controller

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

Plunker

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