角度ng重复滤波器通过错误的索引

Angular ng-repeat filter passing wrong index

本文关键字:过错 错误 索引 滤波器 ng 角度      更新时间:2023-09-26

我很难弄清楚如何使用过滤器从ng重复传递正确的索引号。我正在使用模态窗口来编辑表中的行。问题是我依靠索引号进行 REST 调用并为我的编辑模式窗口获取正确的数据。

ng-repeat代码:

    <tr ng-repeat="myItem in myItems | filter:{Status :'!Completed'}">
      <td data-title="Title">{{myItem.Title}}</td>
      <td data-title="Category">{{myItem.Category}}</td>
      <td data-title="Priority">{{myItem.Priority}}</td>
      <td data-title="Due Date">{{myItem.DueDate}}</td>
      <td data-title="Due Date">{{myItem.Status}}</td>
      <td data-title="Due Date">{{myItem.AssignedTo}}</td>
      <td data-title="Edit"><span class="mdi-content-create editIcon" data-ng-click="openEditModal($index)" style="cursor:pointer"></span></td>
      <td data-title="Delete"><span style="  margin-left: 10px;" class="mdi-content-clear editIcon" ng-confirm-click="Are you sure you want to delete this request?" confirmed-click="deleteItem($index)" style="cursor:pointer"></span></td>
    </tr>

将索引传递给模态的代码:

$scope.openEditModal = function(index) {
var modalInstance = $modal.open({
    controller: 'modalCtrl',
    templateUrl: 'https://xxxx/App/editModal.html',
    windowClass: "editModal",
    resolve: {
        index: function() {
            return index;
            console.log(index);
        }
    }
});
}

需要索引号来获取当前项目的 ID,以便进行正确的$http get调用。

但是过滤器改变了索引的顺序,我似乎找不到一个好的选择。

有什么建议吗?

溶液:

传递对象/项而不是索引似乎可以完成这项工作:

.HTML:

data-ng-click="openEditModal(myItem)

.JS:

$scope.openEditModal = function(myItem) {
    var idx = $scope.myItems.indexOf(myItem);
    var modalInstance = $modal.open({
        controller: 'modalCtrl',
        templateUrl: 'https://xxxx/App/editModal.html',
        windowClass: "editModal",
        resolve: {
            index: function() {
                return idx
            }
        }
    });
}

我现在可以使用 ID 编辑/删除正确的项目。这当然需要与项目关联的 ID。正如评论中指出的那样,ID在许多情况下可以派上用场。

谢谢你的帮助!

更安全的

替代方案是,为您的对象myItem.id引入一个 unqiue id,并将其用作在 http 请求中加载的资源的标识符。所以你不必依赖$index,这可能会导致一些问题,正如Tomek Sulkowski指出的那样(行为可能会随着不同的角度版本而改变)。

过滤器弄

乱索引是一个常见问题。

您可以通过实现如下逻辑来绕过它:

<tr ng-repeat="myItem in myItems" ng-show="myItem.Status !== 'Completed'">
  <td data-title="Title">{{myItem.Title}}</td>
  <td data-title="Category">{{myItem.Category}}</td>
  <td data-title="Priority">{{myItem.Priority}}</td>
  <td data-title="Due Date">{{myItem.DueDate}}</td>
  <td data-title="Due Date">{{myItem.Status}}</td>
  <td data-title="Due Date">{{myItem.AssignedTo}}</td>
  <td data-title="Edit"><span class="mdi-content-create editIcon" data-ng-click="openEditModal($index)" style="cursor:pointer"></span></td>
  <td data-title="Delete"><span style="  margin-left: 10px;" class="mdi-content-clear editIcon" ng-confirm-click="Are you sure you want to delete this request?" confirmed-click="deleteItem($index)" style="cursor:pointer"></span></td>
</tr>