TheMcMurder
TheMcMurder

Reputation: 758

Angular OrderBy index not functioning

I am setting the default orderby on a directive. On certain click events I'm changing the order by the column that was clicked upon. However when I try to set a default order by the index I get some really strange results.

I've created a Plunker based off the Angular Documentation. My goal is to have the default orderBy (only code shown here) perform no sorting so that I can change the orderBy property later.

Plunker: Plunker Or HTML Below

  <div ng-controller="ExampleController">
    <table class="friend">
      <tr>
        <th>Name</th>
        <th>Phone Number</th>
        <th>index</th>
      </tr>
      <tr ng-repeat="friend in friends | orderBy:'index'">
        <td>{{friend.name}}</td>
        <td>{{friend.phone}}</td>
        <td>{{friends.indexOf(friend)}}</td>
      </tr>
    </table>
  </div>

New Plunker. It appears as if this is a change from Angular 1.2 to 1.3 I tested working code on different versions of angular and in 1.2 you can pass a empty order by and it will order by the index but in 1.3 and 1.4 it sorts differently

Upvotes: 0

Views: 730

Answers (2)

TheMcMurder
TheMcMurder

Reputation: 758

I solved this issue by presorting my list at all times.

Then my function did all the work I was previously relying on Angular to do for me.

As an FYI I also submitted this as a bug to the angularJS team. They reported that it will be fixed in the next release (https://github.com/angular/angular.js/issues/12100)

Upvotes: 0

Numyx
Numyx

Reputation: 1758

You don't need any sorting at all here, the array is already in the order you want it to be. Assuming that you have a variable $scope.orderByField defining which property you want to use for ordering you could do something like:

<tr ng-repeat="friend in (orderByField ? (friends | orderBy : orderByField) : friends)">

So you would use the orderBy filter only if you really need it.

Plunker: http://plnkr.co/edit/kXOSF4adOohDDxLEtnGT?p=preview


Appart from that you can also define a custom comparator method and use it:

$scope.sortByIndex = function(a, b) {
  return $scope.friends.indexOf(a) - $scope.friends.indexOf(b)
}

<tr ng-repeat="friend in friends | orderBy : sortByIndex">

But i wouldn't really recommend to use that, cause you will do unnecessary calculations.

Upvotes: 1

Related Questions