学习Angularjs分页指令
在项目中许多页面都用到了分页,然后每个页面都有许多重复的分页代码,于是自己写了一份简易的分页指令,简化页面的代码,且容易维护,写在博客中当做备份,方便以后查阅。
以下是定义指令及其应用的步骤:
1.指令定义
定义一个js文件,page-directive.js,用来写分页的指令代码,这个文件中包含了分页的模板,以下是js文件中的所有代码:
'use strict'; (function () { angular.module('template/pageinit/pageinit.html', []).run([ '$templatecache',function($templatecache) { $templatecache.put('template/pageinit/pageinit.html', '<ul class="pagination-main">\n'+ ' <li class="prev-page" ng-class="{disabled:pagedata.currentpage==1}" title="首页">\n'+ ' <a href="javascript:void(0);" ng-click="on_loadpage(1)"><span class="fa fa-fast-backward"></span></a>\n'+ ' </li>\n'+ ' <li class="prev-page" ng-class="{disabled:pagedata.currentpage==1 }">\n'+ ' <a href="javascript:void(0);" ng-click="on_prev()" title="上一页"><span class="fa fa-step-backward"></span></a>\n'+ ' </li>\n'+ ' <li class="data-page" ng-repeat="page in pagedata.pages" ng-class="{\'first-page\': page==1, \'last-page\': page==pagedata.totalpage}">\n'+ ' <a ng-if="page!=\'...\'" href="javascript:void(0);" ng-class="{\'bg-custom\': page==pagedata.currentpage}" ng-click="on_loadpage(page, tabdata)">{{ page }}</a>\n'+ ' <a ng-if="page==\'...\'" href="javascript:void(0);" ng-class="{\'bg-custom\': page==pagedata.currentpage}" ng-click="">{{ page }}</a>\n'+ ' </li>\n'+ ' <li class="next-page" ng-class="{disabled:pagedata.currentpage==pagedata.totalpage}">\n'+ ' <a href="javascript:void(0);" ng-click="on_next()" title="下一页"><span class="fa fa-step-forward"></span></a>\n'+ ' </li>\n'+ ' <li class="skip-page"><div><input type="text" placeholder="" ng-model="inpage">\n'+ ' <input type="button" value="跳转" ng-click="on_loadpage(inpage)"></div>\n'+ ' </li>\n'+ ' <li class="data-num"><a class="cursor-text" href="#"><span>共{{pagedata.count}}条</span></a></li>\n'+ '</ul>\n'+ '' ); } ]); angular.module('pageinit', ['template/pageinit/pageinit.html']) .directive('pageinit',['pageinittemplate', function(pageinittemplate) { return { restrict : 'ae', templateurl: function (telement, tattrs) { return tattrs.templateurl || pageinittemplate.getpath(); }, replace : true, scope : { pagedata : '=', prev : '&', next : '&', loadpage : '&' }, link : function(scope, element, attrs) { scope.on_prev = function() { if(scope.prev) { scope.prev(); } }; scope.on_next = function() { if(scope.next) { scope.next(); } }; scope.on_loadpage = function(page) { scope.inpage = undefined; if(scope.loadpage) { scope.loadpage({page: page}); } }; } }; }]) .provider('pageinittemplate', function () { var templatepath = 'template/pageinit/pageinit.html'; this.setpath = function (path) { templatepath = path; }; this.$get = function () { return { getpath: function () { return templatepath; } }; }; }); }).call(window);
2.分页样式控制
建议写在单独的.css文件中,首先新建pagesync.css文件,以下是具体样式
.pagination-main { display: inline-block; padding-left: 0; margin: 0 0; border-radius: 4px; vertical-align: middle; } .pagination-main li.prev-page > a { border: 0; } .pagination-main li.next-page > a { border: 0; border-left: 1px; margin-left: 0; } .pagination-main li.first-page > a { border-top-left-radius: 0; border-bottom-left-radius: 0; } .pagination-main li.last-page > a { border-top-right-radius: 0; border-bottom-right-radius: 0; } .pagination-main li div { width: 80px;border: 1px solid #dddddd;background-color: #ffffff;float: left;padding: 0; } .pagination-main li.skip-page input[type='text'] { width: 24px;height: 20px;border: 0;text-align: center; } .pagination-main li.skip-page input[type='button'] { padding: 0 4px 1px 10px;border: 0;border-left: 1px solid #dddddd;background-color: #ffffff } .pagination-main li.data-num > a { border: 0; margin-left: 0; } .pagination-main > li { display: inline; } .pagination-main > li:first-child > a, .pagination-main > li:first-child > span { /*margin-left: 0; border-top-left-radius: 4px; border-bottom-left-radius: 4px;*/ } .pagination-main > .active > a, .pagination-main > .active > span, .pagination-main > .active > a:hover, .pagination-main > .active > span:hover, .pagination-main > .active > a:focus, .pagination-main > .active > span:focus { z-index: 2; color: #fff; cursor: default; background-color: #428bca; border-color: #428bca; } .pagination-main > li > a, .pagination-main > li > span { position: relative; float: left; /*padding: 6px 12px;*/ padding: 1px 8px; margin-left: -1px; line-height: 1.42857143; color: #428bca; text-decoration: none; background-color: #fff; border: 1px solid #ddd; } .pagination-main > .disabled > span, .pagination-main > .disabled > span:hover, .pagination-main > .disabled > span:focus, .pagination-main > .disabled > a, .pagination-main > .disabled > a:hover, .pagination-main > .disabled > a:focus { color: #999; cursor: not-allowed; background-color: #fff; border-color: #ddd; }
3.分页查询方法
我在factory中自定义了分页查询的方法,共用,方便代码的维护。在angular中与后台的交互默认是异步的,我这里写成同步查询了,首先定义js文件pagesync.service.js,以下是factory的全部内容:
'use strict'; angular.module('app').factory('pagesync', ['$http', '$q', function page($http, $q) { var rowcollectionpage = []; var totalpage = 1; var pages = []; var endpage = 1; var load = function(url, currentpage, pagesize,deferred) { var json = {rowcollectionpage: [], totalpage: 1, currentpage:currentpage ? currentpage:1, pages: []}; $http.get(url).success(function(rows) { rowcollectionpage = setpagerow(rows.list, pagesize); // 获取总页数 totalpage = math.ceil(rows.count / pagesize); endpage = totalpage; // 生成数字链接 if (totalpage <= 7) { pages = getpageslow(totalpage); } else { pages = getpageshigh(currentpage, totalpage); } json.rowcollectionpage = rowcollectionpage; json.totalpage = totalpage==0 ? 1 : totalpage; json.currentpage = currentpage; json.pages = pages; json.count = rows.count; json.pagesize = pagesize; /** * 自定义字段,初始化的时候为before,只要经过该分页方法,则字段值变为after * before表示未经过该分页方法,after表示经过该分页方法, * 前台页面加载的规则:为before时表示表格无数据,为after且patadata.count==0时无数据,否则视为有数据, * 也可以说是记录的一个时间状态(访问数据前及返回数据后) */ json.loadtime = 'after'; deferred.resolve(json); }); return deferred.promise; }; // 总页数小于等于7时 显示所有的页数 var getpageslow = function(totalpage) { var temp = []; for (var i=1; i<totalpage+1; i++) { temp.push(i); } return temp; }; // 总页数大于7时 根据当前页获取7个页码数 var getpageshigh = function(currentpage, totalpage) { var temp = []; if (currentpage < 4) { temp = [1, 2, 3, 4, 5, '...', totalpage]; } else if ((totalpage - currentpage) <= 3) { temp = [ totalpage - 6, totalpage - 5, totalpage - 4, totalpage - 3, totalpage - 2, totalpage - 1, totalpage ]; } else { temp = [ currentpage - 2, currentpage - 1, currentpage, currentpage + 1, currentpage + 2, '...', totalpage ]; } return temp; }; // 项目中table的高度是根据浏览器窗口的高度计算的来的,是动态的 // 因为要把分页固定在table最下方,所以无数据的用空行进行代替 var setpagerow = function(rowarr, pagesize) { var temp = []; if (rowarr != undefined) { for (var i = 0; i < rowarr.length; i++) { temp.push(rowarr[i]); } for (var j = 0; j < pagesize - rowarr.length; j++) { temp.push({}); } } else { for (var k = 0; k < pagesize; k++) { temp.push({}); } } return temp; }; return { load: function(url, currentpage, pagesize) { var deferred = $q.defer(); url += '&' + currentpage + '&' + pagesize; return load(url, currentpage, pagesize, deferred); }, next: function(url, currentpage, pagesize) { var deferred = $q.defer(); if (currentpage < endpage) { currentpage++; } url += '&' + currentpage + '&' + pagesize; return load(url, currentpage, pagesize, deferred); }, prev: function(url, currentpage, pagesize) { var deferred = $q.defer(); currentpage--; url += '&' + currentpage + '&' + pagesize; return load(url, currentpage, pagesize, deferred); }, loadpage: function(url, currentpage, pagesize, page) { var deferred = $q.defer(); if (currentpage != page) { currentpage = page; url += '&' + currentpage + '&' + pagesize; return load(url, currentpage, pagesize, deferred); } } } }]);
4.使用指令
1).页面上的代码:
我的代码中分页是写在table中的tfoot里面了,prev()、next()、loadpage(page)均为在页面对应的controller中定义的方法
<table> <thead> <tr> <th>序号</th> <th>列名1</th> <th>列名2</th> <th style="width: 150px;text-align: center;">操作</th> </tr> </thead> <tbody> <tr ng-if="!notabledata" ng-repeat="row in pagedata.rowcollectionpage"> <td>{{!!row.id ? $index+1+(pagedata.currentpage-1)*pagesize : ''}}</td> <td>{{row.args1}}</td> <td>{{row.args2}}</td> <td style="text-align: center;"><a href='#'>修改</a></td> </tr> <tr ng-if="notabledata" ng-repeat="data in pagedata.rowcollectionpage"> <td ng-if="$index == 0" colspan="4" style="text-align: center;">没有数据!</td> <td ng-if="$index != 0" colspan="4"></td> </tr> </tbody> <tfoot> <tr> <td style="text-align: center;" colspan="6"> <div> <page-init page-data="pagedata" prev="prev()" next="next()" load-page="loadpage(page)"></page-init> </div> </td> </tr> </tfoot> </table>
2).controller中的代码
首先要引用factory,将pagesync在controller中引用,如下:
angular.module('app').controller('myctrl', function(pagesync) {});
在分页查询之前要做一些准备工作:
//pagedata中设置分页数据集合、总页数、页码集合、数据总数,loadtime为自定义的参数,用来记录时间状态(访问数据前及返回数据后)
$scope.pagedata = {rowcollectionpage: [], totalpage: 1, currentpage:1, pages: [],count: 0, loadtime: 'before'};
// 这里用来计算table的高度,根据实际情况来。
$scope.tabheight = $scope.height-48-37-10-42-5;
// 计算实际中一页有多少行数据
$scope.pagesize = parseint(($scope.tabheight-15-34-34-39)/34);
然后再controller中写如下的方法
// 分页查询 $scope.load = function(row) { $scope.surgeonpagedata.rowcollectionpage = common.setpagerow([],$scope.pagesize); $scope.nosurgeondata = false; $scope.surgeonpagedata.loadtime = 'before'; pagesync.load(url, $scope.pagedata.currentpage, $scope.pagesize).then(function(data) { $scope.pagedata = data; if(($scope.pagedata.loadtime=='after'&& $scope.pagedata.count==0) || $scope.pagedata.loadtime=='before') { $scope.notabledata = true; } }); }; // 下一页 $scope.next = function() { if ($scope.pagedata.currentpage < $scope.pagedata.totalpage) { pagesync.next(url, $scope.pagedata.currentpage, $scope.pagesize).then(function(data) { $scope.pagedata = data; }); } }; // 上一页 $scope.prev = function() { if ($scope.pagedata.currentpage > 1) { pagesync.prev(url, $scope.pagedata.currentpage, $scope.pagesize).then(function (data) { $scope.pagedata = data; }); } }; // 点击页码跳转 $scope.loadpage = function(page) { $scope.inpage = undefined; var intpage; if (typeof page == 'string') { if(page!="") { intpage = parseint(page, 10); } else { intpage = 0; } } else { intpage = page; } if ($scope.pagedata.totalpage <= 1) { } else if (intpage == undefined || intpage == null) { alert('请填写跳转页码!'); } else if(intpage <= 0 || intpage > $scope.pagedata.totalpage) { alert('跳转页码应大于0,小于总页数'+$scope.pagedata.totalpage); } else if ($scope.pagedata.currentpage != page) { pagesync.loadpage(url, $scope.pagedata.currentpage, $scope.pagesize, page).then(function (data) { $scope.pagedata = data; }); } };
5.结果
最终的实现效果如下图:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
下一篇: 必须掌握的CSS文字样式