Ionic toggle group check one item and uncheck the

2019-08-01 11:04发布

问题:

I have created a toggle view to select available items in Ionic, and if anyone of the item were selected, I want to uncheck all the other items. I also have a scan function which allows me to dynamically update the items list

I'm fairly new to ionic, so I just have the following code in my settings.html

<ion-toggle ng-repeat="item in itemsList"
         ng-model="item.checked">
    {{ item.text }}
</ion-toggle>

and then I have created a simple settings.js:

(function () {
    'use strict';

    angular.module('i18n.setting').controller('Settings', Settings);
    SettingController.$inject = ['$scope'];

    function Settings($scope){
        $scope.settingsList = [
            {text: "item1", checked: true},
            {text: "item2", checked: false}
        ];
    }
})();

I know ng-model="item.checked" will do the job of changing the attribute $scope.settingsList.checked for me. But what I want to know this how to use it to check one items and uncheck all the other ones?

回答1:

loop through all the items, set the checked state of all the values to false and then your html code must be:

<ion-toggle ng-repeat="item in settingsList"
                ng-model="item.checked" 
                ng-checked="item.checked" style="border:1px solid #28a54c" ng-change="toggleChange(item)">
      {{ item.text }}
</ion-toggle>

Your Controller code

$scope.toggleChange = function(item) {
      if (item.checked == true) {
          for(var index = 0; index < $scope.settingsList.length; ++index)
              $scope.settingsList[index].checked = false;
          item.checked = true;
      } else {
        item.checked = false
      }
};

And it's better to use forEach in async environment.