ng-repeat元素# 39;索引在排序时改变

ng-repeat elements' indexes changing on sort

本文关键字:排序 改变 索引 元素 ng-repeat      更新时间:2023-09-26

我有一个HTML表,其中使用ng-repeat创建行,使用对象数组中对象的属性创建数据。它们按名称列的字母顺序排序。我用ng-show, ng-focus和ng-blur设置了一些简单的编辑,这样就不需要保存按钮或类似的东西了。

但是,在编辑name列时,如果我键入的第一个字母将导致该行在表中的位置较低,则在我仍在键入时对表进行排序。我尝试创建一个"临时"对象数组,将原始数组复制到其中,编辑时修改"临时"数组,然后在编辑完成时将临时数组复制到原始数组中。这行不通;同样的事情还是发生了。

稍作研究后,我了解到临时数组和原始数组可能指向相同的数据,因此我尝试了多种克隆数组的方法。我终于让它工作了……只有一个例外:当我编辑要排序较低的对象时,它移动了。当我试图再次编辑它时,它做了各种各样随机的、意想不到的事情。

经过一些诊断后,我发现表中对象的索引(从$index获得)在排序时被更改了。例如:

Table
-------------------------------------
|Name    |Age     |Phone   |Index   |
-------------------------------------
|George  |25      |928-7495|0       |
|John    |34      |342-0673|1       |
|Megan   |28      |834-1943|2       |
|Susan   |19      |274-8104|3       |
-------------------------------------

如果我将George改为Tim,则该对象的索引也变为3。所有其他指标保持不变。有人能告诉我为什么会发生这种情况和/或给我建议如何解决这个问题吗?

显然,我只是没有意识到每次更改数据或数据排序时索引都会发生变化。在将索引添加为对象的属性后,一切都如预期的那样工作。

这就是我如何使用orderBy Angularjs过滤器,它的列排序在单击时反转。"th"中的"a"标签控制行为。我在一个指令中有这个,这是推荐的,但代码可以在控制器中。

我使用了Angularjs的orderBy过滤器。

$filter('orderBy')(array, expression, reverse)
// This is the order of properties in the code below that looks like this
// $scope.rows = angularSortBy( $scope.rows, columnName, toggleOrderDirection( columnName ));

每一列都有一个叫做

的多箭头按钮
<i class="fa fa-sort"></i>

列应该是这样的…

$scope.columns = { columnOne: { label: 'Column One', orderDirection: true, selected: false },
    columnTwo: { label: 'Column Two', orderDirection: true, selected: false },
    columnThree: { label: 'Column Three', orderDirection: true, selected: true }};

和行可以是任何你想要的…

<table>
  <tr>
    <th>Sort By</th>
    <th ng-repeat="(key, value) in columns">
      <a href="" ng-click="orderBy( key )">{{ value.label }}</a>
      <span ng-if="value.selected">
      (<i class="fa fa-sort"></i>) // font-awesome arrow font.
    </th>
  </tr>
  <tr ng-repeat="row in rows">// stuff here</tr>

var angularSortBy = $filter( 'orderBy' ); // use Angular's built in filter to sort table.
$scope.orderBy = function( columnName ){
  resetAllSelectedStates(); // sets column.selected prop to false.
  setAsSelected( columnName, true );
  $scope.rows = angularSortBy( $scope.rows, columnName, toggleOrderDirection( columnName ));
}
function resetAllSelectedStates(){
  Object.keys( $scope.columns ).forEach( resetColumnPropertyToDefault );
}
function resetColumnPropertyToDefault( name ){
  $scope.columns[ name ].selected = false;
}
function setAsSelected( name ){
  $scope.columns[ name ].selected = true;
}
function toggleOrderDirection( name ){
    return $scope.columns[ name ].orderDirection = !$scope.columns[ name ].orderDirection;
}