In my table, each row contains a checkbox and there is also a checkbox to check all rows and send the ID of the selected/all rows as JSON object.
I have an array of objects from the server-side response (with pagination enabled) stored in the itemsList $scope variable.
Here is the code I am using:
View
<table class="table">
<thead>
<tr>
<th><input type="checkbox" ng-model="allItemsSelected ng-change="selectAll()"></th>
<th>Date</th>
<th>ID</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in itemsList track by $index" ng-class="{selected: item.isChecked}">
<td>
<input type="checkbox" ng-model="item.isChecked" ng-change="selectItem(item)">
</td>
<td>{{item.date | date:'dd-MM-yyyy'}}</td>
<td>{{item.id}}</td>
</tr>
</tbody>
</table>
Controller
$scope.itemsList = [
{
id : 1,
date : '2019-04-04T07:50:56'
},
{
id : 2,
date : '2019-04-04T07:50:56'
},
{
id : 3,
date : '2019-04-04T07:50:56'
}
];
$scope.allItemsSelected = false;
$scope.selectedItems = [];
// This function gets executed when an entity in the table is checked
$scope.selectItem = function (item) {
// If any entity is not checked, then uncheck the "allItemsSelected" checkbox
for (var i = 0; i < $scope.itemsList.length; i++) {
if (!this.isChecked) {
$scope.allItemsSelected = false;
$scope.selectedItems.push(item.id);
return;
}
}
// If all entities are checked, check the "allItemsSelected" checkbox
$scope.allItemsSelected = true;
};
// This function executes when the checkbox in the table header is checked
$scope.selectAll = function() {
// Loop through all the entities and set their isChecked property
for (var i = 0; i < $scope.itemsList.length; i++) {
$scope.itemsList[i].isChecked = $scope.allItemsSelected;
$scope.selectedItems.push($scope.itemsList[i].id);
}
};
Issues I'm facing...
- If you check the fiddle example, you will see that on the checkAll() function call, the array is updated with all available items. However, clicking again on checkAll() adds another row to the same object array instead of removing it.
- I also want the ability to add or remove items from the array when clicking on any row's checkbox.
- If I manually check all checkboxes, the header checkbox should also be checked.