在ng-repeat中找到使用orderBy的下一个项目

时间:2014-12-04 01:00:54

标签: javascript angularjs angularjs-scope angularjs-ng-repeat angularjs-filter

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

我使用ng-repeat呈现一个列表。我想允许用户通过单击列标题对此列表进行排序。我使用orderBy过滤器实现了这一点。

问题是我需要一种方法来导航到列表中的下一个项目(如用户所见)。并且还从原始数组中检索该实际项目。

这应该是范围的功能。 (事实上​​,当按下某个快捷键时会调用它。)

我可以维持目前的指数'在控制器中。但是,从控制器中解析实际项目是不可能的,因为原始数组的索引与ng-repeat显示的索引不同。

请参阅此处的完整演示: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>

下一项:

$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;
}

任何想法都将受到赞赏!

1 个答案:

答案 0 :(得分:2)

使用此:

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

$filter("orderBy")会返回正确的过滤条件;然后在获得所选索引之前过滤(订购)卡片。

更新了小提琴:http://jsfiddle.net/prankol57/8teh2sn0/

有关详细信息,请参阅the documentation for filterHow to use a filter in javascript instead of the Html