Javascript 使用ng repeat在列表上分页

Javascript 使用ng repeat在列表上分页,javascript,angularjs,paginate,Javascript,Angularjs,Paginate,我正在尝试将页面添加到列表中。我遵循了AngularJS教程,关于智能手机的教程,我试图只显示一定数量的对象。这是我的html文件: <div class='container-fluid'> <div class='row-fluid'> <div class='span2'> Search: <input ng-model='searchBar'> Sort by:

我正在尝试将页面添加到列表中。我遵循了AngularJS教程,关于智能手机的教程,我试图只显示一定数量的对象。这是我的html文件:

  <div class='container-fluid'>
    <div class='row-fluid'>
        <div class='span2'>
            Search: <input ng-model='searchBar'>
            Sort by: 
            <select ng-model='orderProp'>
                <option value='name'>Alphabetical</option>
                <option value='age'>Newest</option>
            </select>
            You selected the phones to be ordered by: {{orderProp}}
        </div>

        <div class='span10'>
          <select ng-model='limit'>
            <option value='5'>Show 5 per page</option>
            <option value='10'>Show 10 per page</option>
            <option value='15'>Show 15 per page</option>
            <option value='20'>Show 20 per page</option>
          </select>
          <ul class='phones'>
            <li class='thumbnail' ng-repeat='phone in phones | filter:searchBar | orderBy:orderProp | limitTo:limit'>
                <a href='#/phones/{{phone.id}}' class='thumb'><img ng-src='{{phone.imageUrl}}'></a>
                <a href='#/phones/{{phone.id}}'>{{phone.name}}</a>
                <p>{{phone.snippet}}</p>
            </li>
          </ul>
        </div>
    </div>
  </div>
我还有一个模块,用于从json文件中检索数据

angular.module('phonecatServices', ['ngResource']).
    factory('Phone', function($resource){
        return $resource('phones/:phoneId.json', {}, {
            query: {method: 'GET', params:{phoneId:'phones'}, isArray:true}
        });
    });

如果您没有太多的数据,您完全可以通过将所有数据存储在浏览器中并过滤在特定时间可见的内容来进行分页

下面是一个简单的分页示例:

该示例位于angular.js github wiki上的小提琴列表中,这应该会有所帮助:

编辑: 到
(如果有45个结果,则不会显示“1/4.5”)

我刚刚制作了一个JSFIDLE,使用 使用Twitter引导代码生成:

查看此指令:


它可以自动排序和分页,并为您提供足够的自由来定制您想要的表格/列表。

我构建了一个模块,使内存分页变得非常简单

它允许您通过简单地将
ng repeat
替换为
dir paginate
,将每页的项目指定为管道过滤器,然后以单个指令

以Tomarto提出的原始示例为例,它如下所示:

<ul class='phones'>
    <li class='thumbnail' dir-paginate='phone in phones | filter:searchBar | orderBy:orderProp | limitTo:limit | itemsPerPage: limit'>
            <a href='#/phones/{{phone.id}}' class='thumb'><img ng-src='{{phone.imageUrl}}'></a>
            <a href='#/phones/{{phone.id}}'>{{phone.name}}</a>
            <p>{{phone.snippet}}</p>
    </li>
</ul>

<dir-pagination-controls></dir-pagination-controls>
  • {{phone.snippet}

控制器中不需要任何特殊的分页代码。所有这些都由模块内部处理

演示:
来源:这是一个演示代码,其中使用AngularJS进行分页+过滤:

JS:

var app=angular.module('myApp', []);

// alternate - https://github.com/michaelbromley/angularUtils/tree/master/src/directives/pagination
// alternate - http://fdietz.github.io/recipes-with-angular-js/common-user-interface-patterns/paginating-through-client-side-data.html

app.controller('MyCtrl', ['$scope', '$filter', function ($scope, $filter) {
    $scope.currentPage = 0;
    $scope.pageSize = 10;
    $scope.data = [];
    $scope.q = '';

    $scope.getData = function () {
      // needed for the pagination calc
      // https://docs.angularjs.org/api/ng/filter/filter
      return $filter('filter')($scope.data, $scope.q)
     /* 
       // manual filter
       // if u used this, remove the filter from html, remove above line and replace data with getData()

        var arr = [];
        if($scope.q == '') {
            arr = $scope.data;
        } else {
            for(var ea in $scope.data) {
                if($scope.data[ea].indexOf($scope.q) > -1) {
                    arr.push( $scope.data[ea] );
                }
            }
        }
        return arr;
       */
    }

    $scope.numberOfPages=function(){
        return Math.ceil($scope.getData().length/$scope.pageSize);                
    }

    for (var i=0; i<65; i++) {
        $scope.data.push("Item "+i);
    }
  // A watch to bring us back to the 
  // first pagination after each 
  // filtering
$scope.$watch('q', function(newValue,oldValue){             if(oldValue!=newValue){
      $scope.currentPage = 0;
  }
},true);
}]);

//We already have a limitTo filter built-in to angular,
//let's make a startFrom filter
app.filter('startFrom', function() {
    return function(input, start) {
        start = +start; //parse to int
        return input.slice(start);
    }
});
var-app=angular.module('myApp',[]);
//替代-https://github.com/michaelbromley/angularUtils/tree/master/src/directives/pagination
//替代-http://fdietz.github.io/recipes-with-angular-js/common-user-interface-patterns/paginating-through-client-side-data.html
app.controller('MyCtrl',['$scope','$filter',函数($scope,$filter){
$scope.currentPage=0;
$scope.pageSize=10;
$scope.data=[];
$scope.q='';
$scope.getData=函数(){
//分页计算所需的
// https://docs.angularjs.org/api/ng/filter/filter
返回$filter('filter')($scope.data,$scope.q)
/* 
//手动过滤器
//如果使用此选项,请从html中删除筛选器,删除上面的行并用getData()替换数据
var-arr=[];
如果($scope.q==''){
arr=$scope.data;
}否则{
for(var ea在$scope.data中){
if($scope.data[ea].indexOf($scope.q)>-1){
arr.push($scope.data[ea]);
}
}
}
返回arr;
*/
}
$scope.numberOfPages=函数(){
返回Math.ceil($scope.getData().length/$scope.pageSize);
}

对于(var i=0;i我知道这个线程现在已经很旧了,但我回答它是为了保持更新

对于Angular 1.4及以上版本,您可以直接使用过滤器,它除了接受
限制
参数外,还接受
开始
参数

用法:
{{limito_expression}limitTo:limit:begin}


因此,现在您可能不需要使用任何第三方库来实现类似分页的功能。我创建了一个示例来说明这一点。

当您说要实现下一页和上一页时,您希望分页纯粹在客户端还是在服务器端进行。如果记录数太多,则应选择server端分页。在任何情况下,您都需要开始维护“startIndex”-limit只提供页面上的记录数,除此之外,您还需要了解如何维护当前页面-这可以通过维护startIndex来完成。我的记录数不多。我想做的是使用我已有的控制器(PhoneListCtrl)。我不知道是服务器端还是客户端。对不起!@RuteshMakhijani我对高记录数有类似的要求,请解释对高记录数使用服务器端分页的原因。非常感谢!这正是我想要的。我之前看到过该示例,但它不起作用。现在我注意到有一个little语法错误。“for”语句后缺少一个括号。我添加了括号并在wiki上更新了它。但是如果没有括号,它应该可以工作。哦!没关系。我在返回
input.slice(start)之前添加了
if(input?
条件
,谢谢Andy!和Bart一样,我需要将分页信息传递到调用函数中以获取可分页数据-这类似但不同,在某些情况下可能会有所帮助。您好,这个演示对于我参与的一个项目来说非常方便。我需要添加查看全部或切换分页以及显示每个页面的选项。因此我扩展了演示。非常感谢。很棒的工作。最好更进一步,使列标题动态化,即从items json数组中获取所有唯一的键值,并将其绑定到ng repeat,而不是硬编码值。就像我在这里所做的那样:将所有代码放在controller中只会降低可重用性-似乎缺少:QueryableDomainServiceCollectionView、VirtualQueryableCollectionView、HierarchycalDataCollectionViews这是一个非常好的解决方案,易于调整。在两个绑定元素的数量已达到数千个的复杂场景中使用它,并且它确实不是重构整个代码的选项。您应该用一些解释他介绍了基本原则,也许还升级了AngularJS和Bootstrap版本:)乍一看,这正是我所需要的,但我似乎无法让它正常工作/
var app=angular.module('myApp', []);

// alternate - https://github.com/michaelbromley/angularUtils/tree/master/src/directives/pagination
// alternate - http://fdietz.github.io/recipes-with-angular-js/common-user-interface-patterns/paginating-through-client-side-data.html

app.controller('MyCtrl', ['$scope', '$filter', function ($scope, $filter) {
    $scope.currentPage = 0;
    $scope.pageSize = 10;
    $scope.data = [];
    $scope.q = '';

    $scope.getData = function () {
      // needed for the pagination calc
      // https://docs.angularjs.org/api/ng/filter/filter
      return $filter('filter')($scope.data, $scope.q)
     /* 
       // manual filter
       // if u used this, remove the filter from html, remove above line and replace data with getData()

        var arr = [];
        if($scope.q == '') {
            arr = $scope.data;
        } else {
            for(var ea in $scope.data) {
                if($scope.data[ea].indexOf($scope.q) > -1) {
                    arr.push( $scope.data[ea] );
                }
            }
        }
        return arr;
       */
    }

    $scope.numberOfPages=function(){
        return Math.ceil($scope.getData().length/$scope.pageSize);                
    }

    for (var i=0; i<65; i++) {
        $scope.data.push("Item "+i);
    }
  // A watch to bring us back to the 
  // first pagination after each 
  // filtering
$scope.$watch('q', function(newValue,oldValue){             if(oldValue!=newValue){
      $scope.currentPage = 0;
  }
},true);
}]);

//We already have a limitTo filter built-in to angular,
//let's make a startFrom filter
app.filter('startFrom', function() {
    return function(input, start) {
        start = +start; //parse to int
        return input.slice(start);
    }
});
<div ng-app="myApp" ng-controller="MyCtrl">
  <input ng-model="q" id="search" class="form-control" placeholder="Filter text">
  <select ng-model="pageSize" id="pageSize" class="form-control">
        <option value="5">5</option>
        <option value="10">10</option>
        <option value="15">15</option>
        <option value="20">20</option>
     </select>
  <ul>
    <li ng-repeat="item in data | filter:q | startFrom:currentPage*pageSize | limitTo:pageSize">
      {{item}}
    </li>
  </ul>
  <button ng-disabled="currentPage == 0" ng-click="currentPage=currentPage-1">
        Previous
    </button> {{currentPage+1}}/{{numberOfPages()}}
  <button ng-disabled="currentPage >= getData().length/pageSize - 1" ng-click="currentPage=currentPage+1">
        Next
    </button>
</div>