methuselah methuselah - 6 months ago 33
AngularJS Question

Check/uncheck all feature not working in AngularJS

I have tried to set up a function that can select/unselect all the checkboxes in a view. But it doesn't seem to work at all. Is there something I am missing out?

I based my implementation on the following: http://jsfiddle.net/deeptechtons/TKVH6/.

detail.html

<li class="item item-checkbox">
All Services<br>
<label class="checkbox">
<input type="checkbox" ng-model="selectedAll" ng-click="checkAll()" ng-model="selectedAll">
</label>
</li>
<li class="item item-checkbox" ng-repeat="e in inventory">
{{ e.title }}<br>
<span class="grey-text">&pound;{{ e.price | number: 2 }}</span>
<label class="checkbox">
<input type="checkbox" ng-model="item.selected">
</label>
</li>


controller.js

$scope.checkAll = function () {
if ($scope.selectedAll) {
$scope.selectedAll = true;
} else {
$scope.selectedAll = false;
}
angular.forEach($scope.inventory, function (item) {
item.selected = $scope.selectedAll;
});
};

Answer

This part of your code makes no sense. If the value is true you set it to true, same with false, just remove it.

if ($scope.selectedAll) {
  $scope.selectedAll = true;
} else {
  $scope.selectedAll = false;
}

Also, you would be better off using ng-change instead of ng-click.

Couple other things: you have added ng-model twice to your first input element.

And the main problem is: you're referencing each item in your ng-repeat with e and within the loop you use item.selected. You should be using e.selected or change your ng-repeat definition:

<input type="checkbox" ng-model="e.selected">

OR

<li class="item item-checkbox" ng-repeat="item in inventory">

In case you go with the latter you have to change e.price and e.title to item.price and item.title.