按表排序,但索引不遵循

时间:2015-07-17 14:57:06

标签: javascript angularjs

我有一个json数据表,我可以按各列进行排序。 当我按任何列对其进行排序时,单击按钮"删除"它删除了错误的一个,$ index没有更新,我也不知道如何修复它。

JS代码:

  $scope.friends =
      [{name:'John', phone:'555-1212', age:10},
       {name:'Mary', phone:'555-9876', age:19},
       {name:'Mike', phone:'555-4321', age:21},
       {name:'Adam', phone:'555-5678', age:35},
       {name:'Julie', phone:'555-8765', age:29}];
  $scope.predicate = 'age';
  $scope.reverse = false;
  $scope.order = function(predicate) {
     $scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;
     $scope.predicate = predicate;
  };
  $scope.delete = function (friend, index) {
        $scope.friends.splice(index, 1);
  };

HTML code:

 <table class="friend">
    <tr>
      <th>
        <a href="" ng-click="order('name')">Name</a>
        <span class="sortorder" ng-show="predicate === 'name'" ng-class="{reverse:reverse}"></span>
      </th>
      <th>
        <a href="" ng-click="order('phone')">Phone Number</a>
        <span class="sortorder" ng-show="predicate === 'phone'" ng-class="{reverse:reverse}"></span>
      </th>
      <th>
        <a href="" ng-click="order('age')">Age</a>
        <span class="sortorder" ng-show="predicate === 'age'" ng-class="{reverse:reverse}"></span>
      </th>
    </tr>
    <tr ng-repeat="friend in friends | orderBy:predicate:reverse">
      <td>{{friend.name}}</td>
      <td>{{friend.phone}}</td>
      <td>{{friend.age}}</td>
      <td><button ng-click="delete(friend, $index)">Delete</button></td>
    </tr>
  </table>

Plunker链接:

http://plnkr.co/edit/iFIRQisV3qU21PFtMJdC?p=preview

1 个答案:

答案 0 :(得分:2)

刚刚在plunker

中更新了您的功能

直到你有了对象,不要使用$ index。改为使用对象

    $scope.delete = function (friend) {
        $scope.friends.splice($scope.friends.indexOf(friend), 1);
    };

这样做。