javascript - ng-repeat 中的 Angularjs orderBy 正在影响索引。如何从数组中删除正确的元素?

标签 javascript angularjs

我有一个在表格中显示的值数组。当我不订购它们时,我的删除代码将完全按照预期工作。我想对 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/

相关文章:

javascript - 添加具有特定 ID 的文档而不覆盖现有文档

javascript - 来自另一个 Controller 的 Angular.js 回调

javascript - Angular ng-model 动态 getter 和 setter

javascript - 从服务器向客户端发送消息socket.io

javascript - 如何使用在样式组件中发生变化的类

angularjs - 如何在链式 promise 中间停止/中断

c# - 带有 Web API 2 和 AngularJS 的 MVC5.1

javascript - 如何在 angularjs 中隐藏和显示 HTML 元素?

javascript - 如果屏幕低于 480 像素,则阻止 Javascript 继续执行某个功能

javascript - 溢出可见时背景颜色消失