Reputation: 719
i have a problem with default checked items. The default checkbox is working, but when i press a button to show all checked items, the default checks is not showing(they are showed like unchecked), but if i unchecked it and check it again, then it works. I can't find the problem, this is my code:
<ion-checkbox value="{{godina['title']}}" style="width: 200px;margin: 0 auto;" ng-model="checkItems[godina['title']]" ng-click="print()" ng-checked="godina.checked" ng-repeat="godina in godine">{{godina["title"]}}</ion-checkbox>
JS:
$scope.godine = [
{ id: 'Duh', title: '0',checked : false },
{ id: 'Duh2', title: '1',checked : false },
{ id: 'Duh3', title: '2',checked : true},
]
And this is js for all checked items:
var array = [];
for (i in $scope.checkItems) {
alert($scope.checkItems[i]);
if ($scope.checkItems[i] == true) {
array.push(i);
}
}
What i'm i doing wrong?
Upvotes: 0
Views: 390
Reputation: 30739
You do not need a ng-model
to track the values of the checkbox. What you can do is, simply track the selected checkbox on ng-click
event by passing the entire object as a function parameter of ng-click
and then checking if this object has been selected or not. And if the object (checkbox) is not selected then push this object on the selected checkbox array. But if it is already selected simply remove that from the selected array. Here is the code that works fine
<ion-checkbox type='checkbox' value="{{godina['title']}}" ng-click="print(godina)" ng-checked="godina.checked" ng-repeat="godina in godine">{{godina["title"]}}</ion-checkbox>
Controller code
$scope.checkItems = [];
$scope.godine = [
{ id: 'Duh', title: '0',checked : false },
{ id: 'Duh2', title: '1',checked : false },
{ id: 'Duh3', title: '2',checked : true},
];
angular.forEach($scope.godine, function(value, key){
if(value.checked){
$scope.checkItems.push(value);
}
});
$scope.print = function(godina){
var idx = $scope.checkItems.indexOf(godina);
// Is currently selected
if (idx > -1) {
$scope.checkItems.splice(idx, 1);
}
// Is newly selected
else {
$scope.checkItems.push(godina);
}
console.log($scope.checkItems);
}
Notice that loop. It is for pushing the already selected object in the selection array $scope.checkItems
For your simplicity. Here is the link to JSFIDDLE
Upvotes: 1
Reputation: 407
Change ng- model value and delete ng-checked
<ion-checkbox value="{{godina['title']}}" style="width: 200px;margin: 0 auto;"
ng-model="godina.checked" ng-click="print()" ng-repeat="godina in godine">
{{godina["title"]}}</ion-checkbox>
Upvotes: 0