how to get value of ion-checkbox

2019-05-08 21:40发布

问题:

I display my checkbox list using this code :

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

This is my listPref:

 $scope.listPref = [
    {text: 'Cinema'},
    {text: 'Sport'},
    {text: 'It'} ,
    {text: 'Music'},
    {text: 'Theater'},
    {text: 'Conference'}];

I try this code to get the text of all selected item

 for(var i =0 ; i <$scope.listPref.length ; i++){
console.log($scope.listPref[i].checked.text); 
 } 

I get the message undefined Cannot read property 'text' of undefined at Scope.$scope.pref in my console. Can someone help me please.

回答1:

HTML:

<ion-content>
   <ion-checkbox ng-repeat="item in listPref"
       ng-model="checkItems[item.text]" ng-change="print()">
       {{ item.text }}
   </ion-checkbox>
   <button type="button" name="button" ng-click="save()">Save</button>
</ion-content>

JS (inside controller):

$scope.listPref = [
    {text: 'Cinema'},
    {text: 'Sport'},
    {text: 'It'} ,
    {text: 'Music'},
    {text: 'Theater'},
    {text: 'Conference'}
];

$scope.checkItems = { }

$scope.print = function() {
    console.log($scope.checkItems);
}

$scope.save = function() {
    var array = [];
    for(i in $scope.checkItems) {
        console.log($scope.checkItems[i]);
        if($scope.checkItems[i] == true) {
            array.push(i);
        }
    }
    console.log(array);
}

You can do whatever you want with the values. print() just prints the object of all the values currently checked or unchecked (true/false). save() stores the value of the checked checkbox inside an array and then prints the array. You can do whatever you like with the values, this example stores them in an array and prints to the console so what is happening can easily be seen.

Comment if you have any questions.