2016-04-10 12 views
4

イオン、チェックボックスの値を取得する方法:私はこのコードを使用して、私のチェックボックスのリストを表示

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

は、私が選択したすべてのテキストを取得するには、このコードを試してください:これは私のlistPrefある

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

をアイテム

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

は、私は私のコンソールにメッセージundefinedCannot read property 'text' of undefined at Scope.$scope.prefを取得します。 誰かが私を助けてくれますか?

答えて

5

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(コントローラ内部):

$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); 
} 

あなたが値でやりたいことができます。 print()は、現在チェックまたはチェックされていないすべての値(true/false)のオブジェクトを出力します。 save()は、チェックされたチェックボックスの値を配列内に格納し、配列を出力します。値を使って好きなことをすることができます。この例では配列に格納し、コンソールに出力するので、何が起こっているのかを簡単に確認できます。

ご不明な点がございましたら、ご意見ください。

+0

thnkx、それは完全に動作します。しかし、私はデータベースに格納するテキスト値だけを取得し、 'console.log($ scope.checkItems [i] .text);しようとすると'私はエラー 'undefined'を取得します。あなたの答えに感謝します。 –

+0

あなたは何をデータベースに保存していますか?どのように保存していますか?値、配列、オブジェクトなどによる値? – theblindprophet

+0

また、checkItemsは、キーがチェックボックスにあるテキストであるオブジェクトです。 '{シネマ:真、スポーツ:偽}'。あなたがそれを参照しようとしているので、 "テキスト"と呼ばれるプロパティはありません。 – theblindprophet

関連する問題