angular-pagination.js 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. angular.module('myModule', []).directive('myPagination', function () {
  2. return {
  3. restrict: 'EA',
  4. replace: true,
  5. scope: {
  6. option: '=pageOption'
  7. },
  8. template: '<ul class="pagination" style="padding-left: 50px;">' +
  9. '<li ng-click="pageClick(p)" ng-repeat="p in page" class="{{option.curr==p?\'active\':\'\'}}">' +
  10. '<a href="javascript:;">{{p}}</a>' +
  11. '</li>' +
  12. '</ul>',
  13. link: function ($scope) {
  14. //容错处理
  15. if (!$scope.option.curr || isNaN($scope.option.curr) || $scope.option.curr < 1) $scope.option.curr = 1;
  16. if (!$scope.option.all || isNaN($scope.option.all) || $scope.option.all < 1) $scope.option.all = 1;
  17. if ($scope.option.curr > $scope.option.all) $scope.option.curr = $scope.option.all;
  18. if (!$scope.option.count || isNaN($scope.option.count) || $scope.option.count < 1) $scope.option.count = 10;
  19. //得到显示页数的数组
  20. $scope.page = getRange($scope.option.curr, $scope.option.all, $scope.option.count);
  21. //绑定点击事件
  22. $scope.pageClick = function (page) {
  23. if (page == '«') {
  24. page = parseInt($scope.option.curr) - 1;
  25. } else if (page == '»') {
  26. page = parseInt($scope.option.curr) + 1;
  27. }
  28. if (page < 1) page = 1;
  29. else if (page > $scope.option.all) page = $scope.option.all;
  30. //点击相同的页数 不执行点击事件
  31. if (page == $scope.option.curr) return;
  32. if ($scope.option.click && typeof $scope.option.click === 'function') {
  33. $scope.option.click(page);
  34. $scope.option.curr = page;
  35. $scope.page = getRange($scope.option.curr, $scope.option.all, $scope.option.count);
  36. }
  37. };
  38. //返回页数范围(用来遍历)
  39. function getRange(curr, all, count) {
  40. //计算显示的页数
  41. curr = parseInt(curr);
  42. all = parseInt(all);
  43. count = parseInt(count);
  44. var from = curr - parseInt(count / 2);
  45. var to = curr + parseInt(count / 2) + (count % 2) - 1;
  46. //显示的页数容处理
  47. if (from <= 0) {
  48. from = 1;
  49. to = from + count - 1;
  50. if (to > all) {
  51. to = all;
  52. }
  53. }
  54. if (to > all) {
  55. to = all;
  56. from = to - count + 1;
  57. if (from <= 0) {
  58. from = 1;
  59. }
  60. }
  61. var range = [];
  62. for (var i = from; i <= to; i++) {
  63. range.push(i);
  64. }
  65. range.push('»');
  66. range.unshift('«');
  67. return range;
  68. }
  69. }
  70. }
  71. });