【问题标题】:Locating next item in ng-repeat which uses orderBy在使用 orderBy 的 ng-repeat 中定位下一项
【发布时间】:2015-02-01 18:30:14
【问题描述】:

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

任何想法将不胜感激!

【问题讨论】:

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


    【解决方案1】:

    使用这个:

    $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

    【讨论】:

    • 太棒了!谢谢@soktinpk,我认为使用 Javascript 中的过滤器是我一直在寻找的。​​span>
    猜你喜欢
    • 1970-01-01
    • 2014-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-11
    • 2017-01-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多