如何在angularjs中使用分页?

时间:2016-03-18 06:39:03

标签: javascript jquery angularjs pagination angular-ui-bootstrap

所以我正在开发这个应用程序,我希望将分页应用于模板列表。

模板对象存储在列表中。

我正在页面上显示模板的缩略图,我想为此页面应用分页。 到目前为止,我已尝试过以下解决方案,但它没有成功。

list.html

<div class="container">
<div class="homepage-header">
    <h2 class="homepage-title text-center wow fadeInDown animated" style="visibility: visible; animation-name: fadeInDown; -webkit-animation-name: fadeInDown;"> TEMPLATES </h2>
</div>

<div class="row">
    <div class="col-md-6 col-sm-6" style="text-align: left">
        <div class="form-inline">
            <div class="form-group has-feedback has-clear">
                <input type="text" class="form-control" ng-model="searchParam" ng-model-options="{ debounce: 400 }" placeholder="Search template ..."
                />
                <a class="glyphicon glyphicon-remove-sign form-control-feedback form-control-clear" ng-click="searchParam = '';
                  retreivePageData(0);" ng-show="searchParam" style="pointer-events: auto; "></a>
            </div>
        </div>
    </div>
    <div class="col-md-6 col-sm-6" style="text-align: right; padding-right: 30px;">
        <div class="form-inline">
            <label>
                <input type="radio" ng-model="selectedOption" value="All" ng-change="retrieveTemplates(selectedOption)"> All
            </label>
            <label>
                <input type="radio" ng-model="selectedOption" value="Annotate" ng-change="retrieveTemplates(selectedOption)"> Annotate
            </label>
            <label>
                <input type="radio" ng-model="selectedOption" value="Rapid" ng-change="retrieveTemplates(selectedOption)"> Component
            </label>               
        </div>
    </div>
</div>

<div class="homepage-ui-showcase-2-css row wow zoomIn animated" style="height: 402px;padding: 5px 0px; visibility: visible; animation-name: zoomIn; -webkit-animation-name: zoomIn;">
    <div ng-repeat="(templateIndex, templateModel) in templatesList | filter:searchParam | limitTo: itemsPerPage">
        <div class="active col-md-3 col-lg-3 col-sm-6 col-xs-12 mix design painting" style="display: inline-block;padding-top: 10px;"
        ng-init="visible=false" ng-mouseover="visible=true" ng-mouseleave="visible=false">
            <div class="portfolio-item shadow-effect-1 boxShadow" style="max-width: 250px;padding:0.3px;border:2px dotted  #bebede;cursor: pointer">
                <div class="mainBadge">
                    <kbd>{{templateModel.type}}</kbd>
                </div>
                <div ng-switch on="{{templateModel.type !== undefined && templateModel.type === 'Annotate'}}">
                    <div ng-switch-when="false" style="height: 130px;" ui-sref="/designer/:pageId({pageId:templateModel.id})" class="portfolio-img ">
                        <i style="opacity:0.4;padding-top:35px;padding-left:15px;margin-left: 30%;" class="fa fa-puzzle-piece fa-4x"></i>
                    </div>
                    <div ng-switch-when="true" style="height: 130px;" ui-sref="annotator/:annotatedTemplateId({annotatedTemplateId:templateModel.id})"
                    class="portfolio-img ">
                        <i style="opacity:0.4;padding-top:35px;padding-left:15px;margin-left: 30%;" class="fa fa-file-image-o fa-4x"></i>
                    </div>
                </div>

                <div class="portfolio-item-content" title="{{templateModel.name}}">
                    <h3 class="header" style="font-size: 13px;text-align: center;display:inline;">
                        {{templateModel.name}}
                    </h3>
                    <small class="pull-right" ng-show="visible" style="display: inline; padding-top: 4px">
                        <div ng-switch on="{{templateModel.type !== undefined && templateModel.type === 'Annotate'}}">
                            <div ng-switch-when="true" href="#" class="btn btn-xs btn-danger" title="Generate Communication"
                             ui-sref="generateCommunication({mode:'A',id: templateModel.id})"
                             ng-disabled="!templateModel.dynamic_entity"> <!--style="color:#9d9d9;"-->
                                <i class="fa fa-file-pdf-o"></i>
                            </div>
                            <div ng-switch-when="false" href="#" class="btn btn-xs btn-danger" title="Generate Communication"
                             ui-sref="generateCommunication({mode:'T',id: templateModel.id})"
                             ng-disabled="!templateModel.dynamic_entity"> <!--style="color:#9d9d9;"-->
                                <i class="fa fa-file-pdf-o"></i>
                            </div>
                        </div>
                    </small>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="row " style="margin-top: 10px; padding-top:0px;">
    <div class="pagination-div pull-right" style="">
        <uib-pagination  ng-model="currentPage" total-items="totalItems" max-size="maxSize" boundary-links="true">
        </uib-pagination>                       
    </div>
</div>

list.controller.js

&#13;
&#13;
'use strict';
angular.module('rapid').controller('HomeListController',
    function($scope, $rootScope, $window, $uibModal, ServiceFactory, toaster, ReadFileService, AnnotationService, AnnotateService, DocumentService) {

        $scope.templatesList = [];
        $scope.filteredTemplates = [];
        $scope.selectedOption = 'All';
        $scope.annotateTemplateMeta = [];
        $scope.rapidTemplateMeta = [];


        $scope.init = function() {

            $scope.selectedOption = "All";
            //$scope.options = [{'label':'All', 'value':'All'}, {'label':'Annotate', 'value':'Annotate'}, {'label':'Component', 'value':'Component'}];
            $scope.retrieveTemplates('All');
            $scope.currentPage = 1;
        };

        $scope.retrieveTemplates = function(selectedOption) {
            $scope.templatesList = [];
            if (selectedOption === 'Annotate') {
                $scope.fetchAnnotationTemplates(selectedOption);
            } else if (selectedOption === 'Rapid') {
                $scope.fetchRapidTemplates(selectedOption);
            } else {
                $scope.fetchAnnotationTemplates(selectedOption);
            }
                       
        };

        $scope.fetchAnnotationTemplates = function(selectedOption) {
            AnnotateService.get().$promise.then(function(result) {
                $scope.annotateTemplateMeta = result[0];
                console.log('Annotated template count :: ' + result[0].length);
                if (selectedOption === 'All') {
                    $scope.fetchRapidTemplates(selectedOption);
                } else {
                    $scope.prepareTemplateList(selectedOption);
                }
            });
        };

        $scope.fetchRapidTemplates = function(selectedOption) {
            ServiceFactory.PagesService.getAllPages().$promise.then(function(result) {
                $scope.rapidTemplateMeta = result[0];
                console.log('Rapid template count :: ' + result[0].length);
                $scope.prepareTemplateList(selectedOption);                
            });
        };

        $scope.prepareTemplateList = function(selectedOption) {
            $scope.itemsPerPage = 8;
            var getPaginatedTemplateList = 'getList';
            //$scope.currentPage = 0;
            if (selectedOption === 'Annotate') {
                $scope.annotateTemplateMeta.forEach(function(annotate) {
                    var templateObject = {};
                    templateObject = { id: annotate.id, name: annotate.name, type: "Annotate", dynamic_entity: annotate.dynamic_entity };
                    $scope.templatesList.push(templateObject);                    
                });

            } else if (selectedOption === 'Rapid') {
                $scope.rapidTemplateMeta.forEach(function(rapidTemplate) {
                    var templateObject = {};
                    templateObject = { id: rapidTemplate._id, name: rapidTemplate.name, type: "Component", dynamic_entity: rapidTemplate.pageObj.entity };
                    $scope.templatesList.push(templateObject);
                });                
            } else {
                $scope.annotateTemplateMeta.forEach(function(annotate) {
                    var templateObject = {};
                    templateObject = { id: annotate.id, name: annotate.name, type: "Annotate", dynamic_entity: annotate.dynamic_entity };
                    $scope.templatesList.push(templateObject);
                });
                $scope.rapidTemplateMeta.forEach(function(rapidTemplate) {
                    var templateObject = {};
                    templateObject = { id: rapidTemplate._id, name: rapidTemplate.name, type: "Component", dynamic_entity: rapidTemplate.pageObj.entity };
                    $scope.templatesList.push(templateObject);
                });

                $scope.totalItems = $scope.templatesList.length;
                $scope.maxSize = 5;                
            }
            console.log($scope.templatesList); 
            console.log($scope.currentPage);
            
        };

        $scope.setPage = function(pageNo) {
            $scope.currentPage = pageNo;
        };

        $scope.pageChanged = function() {
            alert('Page changed to: ' + $scope.currentPage);
            $log.log('Page changed to: ' + $scope.currentPage);
        };

        $scope.init();


        $scope.$watch('currentPage + numPerPage', function() {
            console.log('is it coming.....?');
            var begin = (($scope.currentPage - 1) * $scope.itemsPerPage)
                , end = begin + $scope.itemsPerPage;
            $scope.filteredTemplates = $scope.templatesList.slice(begin, end);
        });

    });
&#13;
&#13;
&#13;

我的代码有什么问题吗?

请提供一些意见。

1 个答案:

答案 0 :(得分:1)

了解如何创建一个处理性能的自定义分页,您将控制分页控制样式。

创建服务以设置分页对象

var rapid = angular.module('rapid');
rapid.service('pagerOptions', function () {
    'use strict';
    return {
        newOptions: function () {
            return {
                totalItems: 0,
                itemsPerPage: 50,
                page: 1,
                sortBy: '',
                isASC: true,
                filters: null,
                sortOptions: {
                    by: '',
                    isASC: true,
                    sort: function (sortBy) {
                        if (sortBy === this.parent.sortBy) {
                            this.parent.isASC = !this.parent.isASC;
                        } else {
                            this.parent.sortBy = sortBy;
                            this.parent.isASC = true;
                        }

                        this.parent.resetPage();
                        if (typeof this.parent.onPageChange === "function")
                            this.parent.onPageChange();
                    }
                },
                resetPage: function () {
                    this.page = 1;
                },
                goToPage: function (page) {
                    this.page = page;
                    if (typeof this.onPageChange === "function")
                        this.onPageChange();
                },
                init: function () {
                    this.sortOptions.parent = this; // it allows the Methods object to know who its Parent is
                    delete this.init; // if you don't need the Init method anymore after the you instanced the object you can remove it
                    return this; // it gives back the object itself to instance it
                }
            }.init();
        }
    };
})

创建一个自定义指令来设计分页模板,如下所示,

    rapid.directive('footerPager', function () {
    return {
        restrict: 'E',
        transclude: true,
        template:
            '<div class="col-xs-9 text-right" ng-cloak>\
                <span ng-if="options.totalItems > options.itemsPerPage">\
                    <pagination \
                        ng-model="options.page" \
                        total-items="options.totalItems" \
                        items-per-page="options.itemsPerPage" \
                        ng-change="options.goToPage(options.page)" \
                        max-size="5" rotate="false" boundary-links="true" \
                        previous-text="&lsaquo;" next-text="&rsaquo;" \
                        first-text="&laquo;" last-text="&raquo;" \
                        class="pagination-sm">\
                    </pagination>\
                </span>\
            </div>\,
        scope: {
            options: '='
        }
    }
});

在cshtml文件中使用上面创建的自定义指令,如下所示,

       <footer-pager options="pagingOptions" id="footer"/>

在相应的controller.js文件中,通过调用上述创建的服务的'newOptions'方法创建并设置'pagerOptions'对象,

    rapid.controller('HomeListController',    
    ['$scope', 'adminSvc','pagerOptions',                                                                                       
    function auditLogCtrl($scope,adminSvc,pagerOptions) {       
    $scope.pagingOptions = pagerOptions.newOptions();
    $scope.pagingOptions.sortBy = "CreatedDate";
    $scope.pagingOptions.itemsPerPage = 10;
    $scope.pagingOptions.onPageChange = loadData; //loadData is a method load the data to the page.
    var numberOfSearchPerfomed = 0;
    $scope.data= {};

    function loadData() {
        $scope.pagingOptions.filters = selectedFilters;
        service.getData(vm.pagingOptions) //Method will fetch data from db and show in the view based on pagingOptions.
            .success(function (result) {
                $scope.data= result.Data;
                $scope.pagingOptions.totalItems = result.TotalCount; // TotalCount represents the total number of records not page wise.
                $scope.enableResetButton = numberOfSearchPerfomed >= 1;
            });
    }

    loadData();
}])