AngularJS - How to access to the next item from a ng-repeat in the controller

天大地大妈咪最大 提交于 2019-12-06 22:54:00

问题


I'd like to access to the parameters of the next item on screen when clicking on a button.

I use a ng-repeat in my html file:

<li ng-repeat="item in items | filter:query" ng-show="isSelected($index)">
    <a href="" ng-click="itemNext()"><img src="xxx.jpg" /></a>
</li>

And the index in my Controller with a loop:

$scope.itemNext = function () {
    $scope._Index = ($scope._Index < $scope.nbItems - 1) ? ++$scope._Index : 0;
    $scope.functionToCallWithNextItem(nextItem.param1);
};

A simple $scope.items[$scope._Index].param1 instead of nextItem.param1 wouldn't work as the data is filtered so $index+1 from $scope.items isn't necessarily the good one.

Any idea ?


回答1:


You can assign your filtered data to a variable:

<li ng-repeat="item in (filteredItems = (items | filter:query))">

Then use $index + 1 to get the next item:

<a ng-click="itemNext(filteredItems[$index + 1])">

Demo: http://plnkr.co/edit/OdL5rIxtTEHnQCC3g4LS?p=preview




回答2:


It's simpy that

<div ng-repeat="item in items">
     current: {{item.value}}
     next: {{ items[$index + 1].value}}
     previous: {{ items[$index - 1].value}}
</div>


来源:https://stackoverflow.com/questions/22311232/angularjs-how-to-access-to-the-next-item-from-a-ng-repeat-in-the-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!