AngularJS中使用ui-bootstrap分页获取表格每行真实索引
我来帮你解决分页时$index重置的问题~
为什么第二页及之后$index会从0开始?
当你用employees.slice(((currentPage-1)*itemsPerPage), ((currentPage)*itemsPerPage))生成当前页数据时,ng-repeat实际遍历的是原始数组的一个局部子集。而$index是ng-repeat针对当前遍历的子集生成的局部索引,它只和当前子集的位置有关,和原始数组的全局位置没有关联。所以每切换一页,新的子集都会让$index从0重新开始计数。
如何获取每行的真实全局索引?
你可以通过**当前页码、每页条数、局部$index**计算出全局索引,公式非常简单:
((currentPage - 1) * itemsPerPage) + $index
把这个公式直接用到需要全局索引的场景即可。
针对你的代码修改示例
我调整了代码里的关键部分,你可以直接参考使用:
1. HTML模板部分(替换局部$index为全局索引)
<tr ng-repeat="emp in employees.slice(((currentPage-1)*itemsPerPage), ((currentPage)*itemsPerPage)) "> <td>{{emp.Name}}<br> <div> <a href="#" ng-click="showHideAddNotes(((currentPage - 1) * itemsPerPage) + $index)"> <img src="http://icongal.com/gallery/image/43850/notes_add.png" /> </a> </div> <div class="textarea-container" ng-show="emp.showComment"> <div style="margin-bottom:5px;"> <textarea id="txtVendorNote{{((currentPage - 1) * itemsPerPage) + $index}}" ng-model="inputvendor" name="foo" placeholder="Add comments here..."></textarea> </div> <button class="btn btn-danger btn-sm" style="padding:2px 10px 2px 10px" ng-click="addNote(vendor.VendKey, ((currentPage - 1) * itemsPerPage) + $index)">Save</button> </div> </td> <td>{{emp.City}}</td> <td>{{emp.Country}}</td> </tr>
(注:我还帮你修正了ng-modal的拼写错误,应该是ng-model)
2. JS控制器部分(函数逻辑无需改动,参数已适配全局索引)
$scope.showHideAddNotes = function (index) { alert(index); // 现在弹出的是原始数组的全局索引 $scope.employees[index].showComment = !$scope.employees[index].showComment; } $scope.addNote = function (vendkey, index) { var notes = APService.SaveVendorComment($('#txtVendorNote' + index).val(), vendkey).responseJSON; $scope.employees[index].showComment = !$scope.employees[index].showComment; }
额外优化建议
为了让HTML代码更简洁,你可以把全局索引的计算逻辑抽成一个控制器函数:
$scope.getGlobalIndex = function(localIndex) { return ((currentPage - 1) * itemsPerPage) + localIndex; }
之后HTML里就可以用getGlobalIndex($index)替代冗长的公式,维护起来更方便~
内容的提问来源于stack exchange,提问作者PK-1825
相关产品推荐
相关产品推荐

