0

On my page I have angular ui accordion, inside of each panel, I'm rendering list with items and checkboxes, also I have checkbox "select all". For selection method and logic I used this resource. In this resource logic seems working, but however I'm putting this logic to my code, it stops working.

What I want to achieve is when all checkboxes are selected, checkbox "select all" has been selected automatically, and if some of checkboxes is unselect, checkbox "select all" has to be unselect as well.

I have tried multiple suggestions provided here, here, here, but in the end I'm getting the same result.

I appreciate if somebody could help me to resolve my problem.

 $scope.categories = [
{
  id: 1,
  name: "category 1"
},
 {
  id: 2,
  name: "category 2"
},
 {
  id: 3,
  name: "category 3"
}
]

               $scope.selectedAll = false;
                $scope.selectAll = function(array) {
                    $scope.selectedAll = !$scope.selectedAll;
                    angular.forEach(array, function(item) {
                        item.Selected = $scope.selectedAll;
                    });
                };

                $scope.checkIfAllSelected = function(array) {
                    $scope.selectedAll = array.every(function(item) {
                        return item.Selected == true
                    })
                };

html

<div>
<div class="row" ng-class="{'selected': selectedAll, 'default': !selectedAll}">
    <div>Select all
        <input type="checkbox"
               ng-model="selectedAll" ng-click="selectAll(categories)" >
    </div>
</div>
<div class="row" ng-repeat="item in categories | orderBy : 'id'" ng-class="{'selected': item.selected, 'default': !item.selected}">
    <div > {{ item.name }}
        <input type="checkbox"
               ng-model="item.Selected" ng-click="checkIfAllSelected(categories)"
        >
    </div>
</div>

This is my plunker

Community
  • 1
  • 1
antonyboom
  • 1,161
  • 2
  • 17
  • 44

1 Answers1

1

Please take a look at this fork of your plunker: https://plnkr.co/edit/OW3F1VMke9iLuNkt5p3o?p=preview

Two things:
1. It's a good practice to create an object to your view model (you can find it under the name model in the plunker $scope.model. This will solve 2 way data binding issues.
2. I have changed the ng-click to ng-change (this is not part of the solution though - its just more correct in my opinion).

Please let me know if you need more clarifications.

vlio20
  • 8,955
  • 18
  • 95
  • 180
  • there is a small bug with model.selectedAll. If you select all, it is selecting checkboxes in every panel https://plnkr.co/edit/XPdqwAXIVgYDU4rMr5DO?p=preview. But I've got desired result, thanks a lot! – antonyboom Nov 04 '16 at 21:15