TL;博士:http://jsfiddle.net/ajpbuymt/1/
我使用ng-repeat
渲染一个列表。我想允许用户通过单击列标题对此列表进行排序。我使用 orderBy
过滤器实现此功能。
问题是我需要一种方法来导航到列表中的下一个项目(如用户所见)。并从原始数组中检索实际项目。
这应该是作用域上的函数。 (事实上,当按下某个快捷键时,就会调用这个函数。)
我可以在 Controller 中维护“当前索引”。但是,无法从 Controller 解析为实际项目,因为原始数组的索引与 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;
}
任何想法将不胜感激!
最佳答案
使用这个:
$scope.lastData =
$filter("orderBy")($scope.cards, $scope.predicate)[$scope.selectedIndex].name;
$filter("orderBy")
返回正确的过滤器;然后在获取所选索引之前过滤(排序)卡片。
更新的 fiddle :http://jsfiddle.net/prankol57/8teh2sn0/
有关更多信息,请参阅 the documentation for filter或How to use a filter in javascript instead of the Html 。
关于javascript - 定位 ng-repeat 中使用 orderBy 的下一个项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27284511/