How to do paging in AngularJS?

后端 未结 21 2185
轮回少年
轮回少年 2020-11-22 07:17

I have a dataset of about 1000 items in-memory and am attempting to create a pager for this dataset, but I\'m not sure on how to do this.

I\'m using a custom filter

21条回答
  •  时光取名叫无心
    2020-11-22 07:47

    I would like to add my solution that works with ngRepeat and filters that you use with it without using a $watch or a sliced array.

    Your filter results will be paginated!

    var app = angular.module('app', ['ui.bootstrap']);
    
    app.controller('myController', ['$scope', function($scope){
        $scope.list= ['a', 'b', 'c', 'd', 'e'];
    
        $scope.pagination = {
            currentPage: 1,
            numPerPage: 5,
            totalItems: 0
        };
    
        $scope.searchFilter = function(item) {
            //Your filter results will be paginated!
            //The pagination will work even with other filters involved
            //The total number of items in the result of your filter is accounted for
        };
    
        $scope.paginationFilter = function(item, index) {
            //Every time the filter is used it restarts the totalItems
            if(index === 0) 
                $scope.pagination.totalItems = 0;
    
            //This holds the totalItems after the filters are applied
            $scope.pagination.totalItems++;
    
            if(
                index >= (($scope.pagination.currentPage - 1) * $scope.pagination.numPerPage)
                && index < ((($scope.pagination.currentPage - 1) * $scope.pagination.numPerPage) + $scope.pagination.numPerPage)
            )
                return true; //return true if item index is on the currentPage
    
            return false;
        };
    }]);
    

    In the HTML make sure that you apply your filters to the ngRepeat before the pagination filter.

    {{item}}

提交回复
热议问题