2

TL;DR: http://jsfiddle.net/ajpbuymt/1/

I render a list with ng-repeat. I want to allow users to sort this list by clicking on column headers. I implement this using orderBy filter.

The problem is I need a way to navigate to next item in the list (as seen by user). And also retrieve that actual item from the original array.

This should be a function on the scope. (In fact, this will be called when certain shortcut key is pressed.)

I can maintain 'current index' in the controller. But then, it's impossible to resolve to the actual item from the controller, because the index of the original array is not the same as what is shown by ng-repeat.

Please refer to full demo here: http://jsfiddle.net/ajpbuymt/1/.

 <a href="#" ng-click="predicate='name'">By name</a>
 <a href="#" ng-click="predicate='age'">By age</a>
 <a href="#" ng-click="predicate='salary'">By salary</a>

 <ul ng-repeat="card in cards | orderBy:predicate">
    <li><span ng-show="selectedIndex == $index">--></span>
        {{card.name}}, {{ card.age }}, {{ card.salary }}</li>
 </ul>

Next item:

$scope.nextItem = function () {
    $scope.selectedIndex++;
    if ($scope.selectedIndex >= $scope.cards.length) {
        $scope.selectedIndex = 0;
    }
    // How to locate the correct lastData when the list is sorted??
    $scope.lastData = $scope.cards[$scope.selectedIndex].name;
}

Any idea will be appreciated!

Gant
  • 29,661
  • 6
  • 46
  • 65

1 Answers1

2

Use this:

$scope.lastData =
    $filter("orderBy")($scope.cards, $scope.predicate)[$scope.selectedIndex].name;

The $filter("orderBy") returns the correct filter; then you filter (order) the cards before obtaining the selected index.

Updated fiddle: http://jsfiddle.net/prankol57/8teh2sn0/

For more information see the documentation for filter or How to use a filter in javascript instead of the Html.

Community
  • 1
  • 1
soktinpk
  • 3,778
  • 2
  • 22
  • 33
  • Wonderful! Thanks @soktinpk, I think using the filter from Javascript is what I have been looking for. – Gant Dec 04 '14 at 02:10