Receive correct $index after filter use

Asked

Viewed 50 times

1

Hello,

I have an image gallery that contains a search box, basically when the user clicks on an image opens a lightbox with that image.

I’m basically passing the $index for a function that opens the item in that list with the index $Scope.list[lb.index]

the code:

HTML
<input type="text" name="search" id="f_search" ng-model="query.name" />
<ul class="list" ng-show="list.length>0">
    <li ng-repeat="item in list | filter:query">
        <a class="img" ng-style="{'background-image':'url(/uploads/<%item.image%>)'}" ng-click="openLB($index)"></a>
    </li>
</ul>
<div class="lightbox" ng-if="lb.show">
    <a class="arrow" ng-show="list.length>1" ng-click="changeItemLB(lb.index, 'prev')">ANTERIOR</a>
    <a class="arrow" ng-show="list.length>1" ng-click="changeItemLB(lb.index, 'next')">PRÓXIMO</a>
    <div class="holder">
        <img ng-if="list[lb.index].image.length" ng-src="/uploads/<%list[lb.index].image%>" />
    </div>
</div>

Angular
$scope.openLB = function(index) {

    $scope.lb.show = true;
    $scope.lb.index = index;

};
$scope.changeItemLB = function(index, action) {

    var tot = $scope.list.length-1,
        goto = 0;

    if(action=='prev') goto = index==0 ? tot : index-1; 
    if(action=='next') goto = index==tot ? 0 : index+1; 

    $scope.openLB(goto);
}

The problem is when after the search the $index remains the same, which causes the wrong image to be opened. Someone knows how to turn this around?

Thank you

1 answer

0

To use the special property $index you have to add the expression track by $index at the end of ngRepeat:

<li ng-repeat="item in list | filter:query track by $index">

Browser other questions tagged

You are not signed in. Login or sign up in order to post.