I have a small image gallery which has a search box and when the user clicks on a image it'll open a lightbox with that same image.
Basically I'm passing the $index to a function which opens the item in $scope.list[lb.index].
my code:
HTML
<input type="text" 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="prev" ng-show="list.length>1" ng-click="changeItemLB(lb.index, 'prev')"></a>
<a class="next" ng-show="list.length>1" ng-click="changeItemLB(lb.index, 'next')"></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 after the user filters the results (search input), the click still maintains the index from the list without the filter which makes the lightbox open the wrong image. Does anyone know how to solve this?
Thanks
Pass object instead of index
Suppose you have 5 item in your list
filter showing two result.
If you click then $index value will be your current view's index
but your list still then have 5 item.
Try like this
<a class="img" ng-style="{'background-image':'url(/uploads/<%item.image%>)'}" ng-click="openLB(item)"></a>
controller
$scope.openLB = function(item) {
var index = $scope.list.indexOf(item);
$scope.lb.show = true;
$scope.lb.index = index;
};
EDIT
How to get Filtered result
Try like this
view
<li ng-repeat="item in filtered= (list | filter:query)">
controller
$scope.filtered=[];
Now you can get yor filtered list from $scope.filtered
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With