Пример Fiddle
У меня есть таблица, в которой каждая строка имеет флажок и еще один флажок для проверки всех строк (флажки) и отправки идентификатора выбранной / всех строк) как объект JSON.
У меня есть массив объектов из ответа (GET) (разбиение на страницы на стороне сервера включено), и он хранится в itemsList $ scope.
Ниже приведен мой код.
Вид
<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>
Контроллер
$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 executes when entity in 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($scope.itemsList[i].id);
$scope.selectedItems.push(item.id);
return
}
}
//If not the check the "allItemsSelected" checkbox
$scope.allItemsSelected = true;
};
// This executes when checkbox in 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);
}
};
Ниже приведеныпроблемы, с которыми я сталкиваюсь ...
- Если вы проверите пример скрипта, то вы увидите, что в checkAll () массив обновляется со всем доступным списком.Но если снова щелкнуть checkAll () вместо удаления списка из массива, он снова добавит еще одну строку в тот же массив объектов.
- Также я хочу сделать то же самое (добавить / удалить из массива), еслиустановите флажок в любой строке
- Если я установил все флажки вручную, флажок thead также должен быть установлен.