【发布时间】:2019-04-04 12:17:31
【问题描述】:
我有一个表格,其中每一行都有复选框和另一个复选框,用于检查所有行(复选框)并将所选/所有行的 ID 作为 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);
}
};
以下是我面临的问题...
- 如果您检查 fiddle 示例,则可以看到在 checkAll() 上,数组已更新为所有可用列表。但是,如果再次单击 checkAll() 而不是从数组中删除列表,它会再次在同一对象数组上添加另一行。
- 如果单击任何行的复选框,我也想做同样的事情(从数组中添加/删除)
- 如果我手动选中所有复选框,则还应选中 thead 复选框。
【问题讨论】:
-
大家好,这个有什么帮助吗?
-
你能提供一个 JSFIDDLE 来解决这个问题吗?
-
@rahim.nagori 已经完成了,请检查所有问题...
标签: javascript angularjs checkbox angularjs-ng-repeat