Ionic checkbox with ng repeat with only one item selected
Posted By : Milind Ahuja | 29-Jun-2016
In Ionic checkbox is same as the input checkbox in HTML. It's just different in style and look like radio buttons. To create a ion-checkbox, you need a ionic directive "ion-checkbox".
<ion-checkbox>Checkbox Label</ion-checkbox>
In this Blog, I am going show how to use ion-checkbox which looks like radio buttons to actually work like them, i.e only one option selected at a time. Furthermore, I am going to use ion-checkbox with ng-repeat and one without ng-repeat and still make them work together i.e if you select the checkbox which is outside the ng-repeat, the selected checkbox inside the ng-repeat must get deselected and vice versa.
Sometimes there is a need that you can't use ng-repeat as there is some additional UI or any customizations with one of the checkboxes, so you take it outside the ng-repeat and customize it and others inside ng-repeat. The following images will help you to understant better:
In first image the "other" option is out of ng-repeat as the textarea will be shown when it is selected. and in the second image input fields are there in "custom" section so it is outside the ng-repeat.
HTML:
JS:
$scope.selectedTimeOption = {}; $scope.selectedTimeOption.custom = false; $scope.items = [{ title: "1 hour", checked: false }, { title: "15 min.", checked: false }, ]; $scope.updateSelection = function(position, items, title) { if (position > -1) { $scope.selectedTimeOption.custom = false; } angular.forEach(items, function(subscription, index) { if (position != index) { subscription.checked = false; } }); $scope.selected = title; }
EXPLANATION:
The ng-repeat starts from index 0, so we pass a index of -1 in option that is outside the ng-repeat. So it doesn't matter how many items are there in ng-repeat but the index can never be less than 0. So if index is less than 0, custom option is selected and other options in ng-repeat deselected and vice versa.
THANKS
About Author
Milind Ahuja
Milind is a bright Lead Frontend Developer and have knowledge of HTML, CSS, JavaScript, AngularJS, Angular 2+ Versions and photoshop. His hobbies are learning new computer techniques, fitness and interest in different languages.