我有一个在表格中显示的值数组。当我不订购它们时,我的删除代码将完全按照预期工作。我想对 ng-repeat 中的值进行排序,以按 Angular 色名称对数据进行分组,但这会使我的 splice 函数删除错误的值。删除我选择的值的正确方法是什么?
有效的 HTML:
<tbody data-ng-repeat="oneUserRole in ui.userRoleResultsList track by $index">
<tr>
<td>{{oneUserRole.UserId}}</td>
<td>{{oneUserRole.RoleName}}</td>
<td>{{oneUserRole.Details}}</td>
<td class="text-center">
<button type="button" class="btn btn-sm btn-danger" title="Delete" data-ng-click="ui.removeUserRole($index)"><i class="fa fa-trash-o" aria-hidden="true"></i></button>
<td>
</tr>
<tbody>
Html 不起作用(根据需要排序,但由于索引问题,删除不起作用):
<tbody data-ng-repeat="oneUserRole in ui.userRoleResultsList | orderBy: 'RoleName' track by $index">
<tr>
<td>{{oneUserRole.UserId}}</td>
<td>{{oneUserRole.RoleName}}</td>
<td>{{oneUserRole.Details}}</td>
<td class="text-center">
<button type="button" class="btn btn-sm btn-danger" title="Delete" data-ng-click="ui.removeUserRole($index)"><i class="fa fa-trash-o" aria-hidden="true"></i></button>
<td>
</tr>
<tbody>
JavaScript:
$scope.ui.removeUserRole = function (index) {
// remove row from array.
$scope.ui.userRoleResultsList.splice(index, 1);
// other code to remove selected item from db omitted here.
}
最佳答案
如果你愿意改变
<button type="button" class="btn btn-sm btn-danger" title="Delete" data-ng-click="ui.removeUserRole($index)"><i class="fa fa-trash-o" aria-hidden="true"></i></button>
到
<button type="button" class="btn btn-sm btn-danger" title="Delete" data-ng-click="ui.removeUserRole({oneUserRole.UserId)"><i class="fa fa-trash-o" aria-hidden="true"></i></button>
然后让它像这样过滤掉 userId :
$scope.ui.removeUserRole = function (userId) {
for(let i = $scope.ui.userRoleResultsList.length; i > 0; i--) {
if(userId == $scope.ui.userRoleResultsList[i]) {
$scope.ui.userRoleResultsList.splice(i, 1);
break;
}
}
}
我认为应该有效
关于javascript - ng-repeat 中的 Angularjs orderBy 正在影响索引。如何从数组中删除正确的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52970260/