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

All we need is an easy explanation of the problem, so here it is.

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=" rel="nofollow noreferrer noopener"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 ?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 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

Method 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>

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply