Angular ng-repeat 在过滤后保持分页

Angular ng-repeat stay paged after filter

我正在使用 AngularJS 并且我有一个简单的 table 使用 ng-repeat 和过滤器。当我在搜索输入中插​​入任何内容时,它过滤正常,但它保持分页,就像我过滤 table 之前一样。知道为什么会这样吗?

这是我的代码:

//some var initialization
$scope.pagina = {};
$scope.pagina.currentPage = 1,
$scope.pagina.numPerPage = 10,
$scope.pagina.maxSize = 5;

//return from server with data
coresFactory.getCores().then(function(response) {
    $scope.tabelaCores = response.data; 
    $scope.filteredTodos = $scope.tabelaCores.cores.slice(0, 10);
});

//do pagination
$scope.$watch('pagina.currentPage', function() {
    var begin = (($scope.pagina.currentPage - 1) * $scope.pagina.numPerPage),
    end = begin + $scope.pagina.numPerPage;
            
    $scope.filteredTodos = $scope.tabelaCores.cores.slice(begin, end);
},true);
<input ng-model="pesquisaTabela" type="search" style="width:300px;" class="form-control input-inline" placeholder="" aria-controls="sample_1"></label>
<table class="table" style="margin-bottom:5px;border:1px solid #DDDDDD" id="sample_1">
 <thead>
  <tr style="background-color:#F9F9F9">
   <th style="width:100px; text-align:center;"> Id </th>
   <th> Nome </th>
   <th> Plural </th>
   <th style="width:100px; text-align:center;"> Ativo </th>
  </tr>
 </thead>
 <tbody>
  <tr ng-repeat="cor in filteredTodos | filter:pesquisaTabela" ng-click="setSelected(cor.id)" ng-class="{linhaSelected: cor.id === idCorSelecionada}">
   <td style="text-align:center;"> {{cor.id}} </td>
   <td style="text-transform:capitalize"> {{cor.nome}} </td>
   <td style="text-transform:capitalize"> {{cor.plural}} </td>
   <td style="text-align:center;">
    <span ng-if="cor.status=='sim'" class="label label-sm label-success"> Sim </span>
    <span ng-if="cor.status=='nao'" class="label label-sm label-danger"> Não </span>
   </td>
  </tr>
 </tbody>
</table>
<pagination first-text="<<" last-text=">>" next-text=">" previous-text="<" ng-model="pagina.currentPage" total-items="tabelaCores.cores.length" max-size="pagina.maxSize" boundary-links="true"></pagination>

你的各个部分之间有很大的脱节

分页正在处理一个数组,从另一个数组显示,filter 从另一个数组开始,因为当 filter 启动它时 returns 一个新的过滤数组。

按照您组织事物的方式,您的过滤器也无法正常工作。 当您对主数据数组进行切片时,过滤器只会对切片的那部分起作用....而不是整个主数组

为了使分页与过滤同步,您最简单的起点可能是进行您自己的过滤并在分页和 table 之间共享相同的过滤数组。

您还可以使用其他一些内置过滤器,例如 limitTo,它接受 2 个参数 limitbegin。这将帮助您摆脱当前的 slice

有很多可用的 grid/table 指令。 使用其中之一将是我最好的建议

还有另一种方法可以在视图中完成所有这些操作。 ng-repeat 的语法在作用域上创建一个新的过滤数组,因此您可以访问它的长度

<tr ng-repeat="row in filteredData = ( data |filter:pesquisaTabela | limitTo:10:start)">

使用这个你可以将 filteredData 数组传递给分页指令的 total-items

它现在还允许您执行以下操作:

<div> Filtered length is: {{filteredData.length}}</div>