Javascript 使用 ng-repeat 对列表进行分页

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11581209/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 06:23:47  来源:igfitidea点击:

Pagination on a list using ng-repeat

javascriptangularjspaginate

提问by Tomarto

I'm trying to add pages to my list. I followed the AngularJS tutorial, the one about smartphones and I'm trying to display only certain number of objects. Here is my html file:

我正在尝试将页面添加到我的列表中。我遵循了 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>

I've added a select tag with some values in order to limit the number of items that will be displayed. What I want now is to add the pagination to display the next 5, 10, etc.

我添加了一个带有一些值的选择标签,以限制将显示的项目数量。我现在想要的是添加分页以显示接下来的 5、10 等。

I have a controller that works with this:

我有一个控制器可以处理这个:

function PhoneListCtrl($scope, Phone){
    $scope.phones = Phone.query();
    $scope.orderProp = 'age';
    $scope.limit = 5;
}

And also I have a module in order to retrieve the data from the json files.

而且我还有一个模块来从 json 文件中检索数据。

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

回答by Andrew Joslin

If you have not too much data, you can definitely do pagination by just storing all the data in the browser and filtering what's visible at a certain time.

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

Here's a simple pagination example: http://jsfiddle.net/2ZzZB/56/

这是一个简单的分页示例:http: //jsfiddle.net/2ZzZB/56/

That example was on the list of fiddles on the angular.js github wiki, which should be helpful: https://github.com/angular/angular.js/wiki/JsFiddle-Examples

该示例在 angular.js github wiki 上的小提琴列表中,应该会有所帮助:https: //github.com/angular/angular.js/wiki/JsFiddle-Examples

EDIT: http://jsfiddle.net/2ZzZB/16/to http://jsfiddle.net/2ZzZB/56/(won't show "1/4.5" if there is 45 results)

编辑:http: //jsfiddle.net/2ZzZB/16/http://jsfiddle.net/2ZzZB/56/(如果有 45 个结果,则不会显示“1/4.5”)

回答by Spir

I just made a JSFiddle that show pagination + search + order by on each column using Build with Twitter Bootstrapcode: http://jsfiddle.net/SAWsA/11/

我刚刚制作了一个 JSFiddle,使用带有 Twitter Bootstrap代码的Build在每列上显示分页 + 搜索 + 排序 :http: //jsfiddle.net/SAWsA/11/

回答by Michael Bromley

I've built a module that makes in-memory pagination incredibly simple.

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

It allows you to paginate by simply replacing ng-repeatwith dir-paginate, specifying the items per page as a piped filter, and then dropping the controls wherever you like in the form of a single directive, <dir-pagination-controls>

它允许您通过简单地替换ng-repeatwith进行分页dir-paginate,将每页的项目指定为管道过滤器,然后以单个指令的形式将控件放置在您喜欢的任何位置,<dir-pagination-controls>

To take the original example asked by Tomarto, it would look like this:

以 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>

There is no need for any special pagination code in your controller. It's all handled internally by the module.

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

Demo: http://plnkr.co/edit/Wtkv71LIqUR4OhzhgpqL?p=preview

演示:http: //plnkr.co/edit/Wtkv71LIqUR4OhzhgpqL?p=preview

Source: dirPagination of GitHub

来源:GitHub 的 dirPagination

回答by Bharat Gupta

I know this thread is old now but I am answering it to keep things a bit updated.

我知道这个线程现在已经过时了,但我正在回答它以保持更新。

With Angular 1.4 and above you can directly use limitTofilter which apart from accepting the limitparameter also accepts a beginparameter.

使用 Angular 1.4 及更高版本,您可以直接使用limitTo过滤器,它除了接受limit参数还接受begin参数。

Usage: {{ limitTo_expression | limitTo : limit : begin}}

用法: {{ limitTo_expression | limitTo : limit : begin}}

So now you may not need to use any third party library to achieve something like pagination. I have created a fiddleto illustrate the same.

所以现在您可能不需要使用任何第三方库来实现诸如分页之类的功能。我创建了一个小提琴来说明这一点。

回答by Samuel Müller

Check out this directive: https://github.com/samu/angular-table

查看此指令:https: //github.com/samu/angular-table

It automates sorting and pagination a lot and gives you enough freedom to customize your table/list however you want.

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

回答by Brahim LAMJAGUAR

Here is a demo code where there is pagination + Filtering with AngularJS :

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

https://codepen.io/lamjaguar/pen/yOrVym

https://codepen.io/lamjaguar/pen/yOrVym

JS :

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);
    }
});

HTML :

HTML :

<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>