Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angularjs 在筛选后获取$index_Angularjs - Fatal编程技术网

Angularjs 在筛选后获取$index

Angularjs 在筛选后获取$index,angularjs,Angularjs,我有一个小的图像库,它有一个搜索框,当用户点击一个图像时,它会打开一个具有相同图像的灯箱 基本上,我将$index传递给一个函数,该函数在$scope.list[lb.index]中打开该项 我的代码: HTML <input type="text" ng-model="query.name" /> <ul class="list" ng-show="list.length>0"> <li ng-repeat="item in list | filte

我有一个小的图像库,它有一个搜索框,当用户点击一个图像时,它会打开一个具有相同图像的灯箱

基本上,我将$index传递给一个函数,该函数在$scope.list[lb.index]中打开该项

我的代码:

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);
}
HTML
" /> 有棱角的 $scope.openLB=函数(索引){ $scope.lb.show=true; $scope.lb.index=索引; }; $scope.changeItemLB=函数(索引、操作){ var tot=$scope.list.length-1, goto=0; 如果(action='prev')goto=index==0?tot:index-1; 如果(action=='next')goto=index==tot?0:index+1; $scope.openLB(goto); }
问题是,在用户过滤结果(搜索输入)后,单击仍会保留列表中的索引,而不使用过滤器,这会使lightbox打开错误的图像。有人知道如何解决此问题吗


谢谢

传递对象而不是索引

假设您的列表中有5项

显示两个结果的过滤器

如果单击,则$index值将是当前视图的索引

但你的清单上还有5项

像这样试试

<a class="img" ng-style="{'background-image':'url(/uploads/<%item.image%>)'}" ng-click="openLB(item)"></a>
编辑

如何得到过滤结果

像这样试试

查看

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

现在你可以从
$scope.filtered

中获得你的筛选列表。我过去处理这个问题的方法是将实际对象传递给控制器函数,并使用indexOf在列表中查找它的索引。我不确定这是否接近最佳实践,但它对我有效。好的,我来试试,谢谢,传递对象。不是吗通常,传递$index是一种很好的做法(出于您所经历的原因)。我之所以传递$index,是因为lightbox有“上一个”和“下一个”“功能性,这就是为什么我认为传递$indexIt更容易工作的原因,我只需要调整上一个/下一个功能:)无论如何,要得到已经过滤的孔列表,lightbox只在过滤的列表上运行上一个和下一个?视图部分解决了我的问题。当您为多个ng repeat+filter共享相同的$scope.variable时。您需要一个唯一的标识符来根据过滤结果区分其长度。
<li ng-repeat="item in filtered= (list | filter:query)">
$scope.filtered=[];