Phuki
Phuki

Reputation: 33

Order by table but the index doesn't follow

I have a table of json data, I can sort it by the various columns. When I sort it by any columns and click on the button "Delete" it removes the wrong one, the $index isn't updated and I don't know how to fix it.

JS code :

  $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 link :

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

Upvotes: 0

Views: 45

Answers (1)

Okazari
Okazari

Reputation: 4597

Just updated your function in the plunker.

Till you have the object, don't use the $index. Use the object instead

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

This do the work.

Upvotes: 2

Related Questions