angular-dirPagination.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  1. /**
  2. * dirPagination - AngularJS module for paginating (almost) anything.
  3. *
  4. *
  5. * Credits
  6. * =======
  7. *
  8. * Daniel Tabuenca: https://groups.google.com/d/msg/angular/an9QpzqIYiM/r8v-3W1X5vcJ
  9. * for the idea on how to dynamically invoke the ng-repeat directive.
  10. *
  11. * I borrowed a couple of lines and a few attribute names from the AngularUI Bootstrap project:
  12. * https://github.com/angular-ui/bootstrap/blob/master/src/pagination/pagination.js
  13. *
  14. * Copyright 2014 Michael Bromley <[email protected]>
  15. */
  16. (function() {
  17. /**
  18. * Config
  19. */
  20. var moduleName = 'angularUtils.directives.dirPagination';
  21. var DEFAULT_ID = '__default';
  22. /**
  23. * Module
  24. */
  25. var module;
  26. try {
  27. module = angular.module(moduleName);
  28. } catch(err) {
  29. // named module does not exist, so create one
  30. module = angular.module(moduleName, []);
  31. }
  32. module
  33. .directive('dirPaginate', ['$compile', '$parse', 'paginationService', dirPaginateDirective])
  34. .directive('dirPaginateNoCompile', noCompileDirective)
  35. .directive('dirPaginationControls', ['paginationService', 'paginationTemplate', dirPaginationControlsDirective])
  36. .filter('itemsPerPage', ['paginationService', itemsPerPageFilter])
  37. .service('paginationService', paginationService)
  38. .provider('paginationTemplate', paginationTemplateProvider)
  39. .run(['$templateCache',dirPaginationControlsTemplateInstaller]);
  40. function dirPaginateDirective($compile, $parse, paginationService) {
  41. return {
  42. terminal: true,
  43. multiElement: true,
  44. compile: dirPaginationCompileFn
  45. };
  46. function dirPaginationCompileFn(tElement, tAttrs){
  47. var expression = tAttrs.dirPaginate;
  48. // regex taken directly from https://github.com/angular/angular.js/blob/master/src/ng/directive/ngRepeat.js#L211
  49. var match = expression.match(/^\s*([\s\S]+?)\s+in\s+([\s\S]+?)(?:\s+track\s+by\s+([\s\S]+?))?\s*$/);
  50. var filterPattern = /\|\s*itemsPerPage\s*:[^|]*/;
  51. if (match[2].match(filterPattern) === null) {
  52. throw 'pagination directive: the \'itemsPerPage\' filter must be set.';
  53. }
  54. var itemsPerPageFilterRemoved = match[2].replace(filterPattern, '');
  55. var collectionGetter = $parse(itemsPerPageFilterRemoved);
  56. addNoCompileAttributes(tElement);
  57. // If any value is specified for paginationId, we register the un-evaluated expression at this stage for the benefit of any
  58. // dir-pagination-controls directives that may be looking for this ID.
  59. var rawId = tAttrs.paginationId || DEFAULT_ID;
  60. paginationService.registerInstance(rawId);
  61. return function dirPaginationLinkFn(scope, element, attrs){
  62. // Now that we have access to the `scope` we can interpolate any expression given in the paginationId attribute and
  63. // potentially register a new ID if it evaluates to a different value than the rawId.
  64. var paginationId = $parse(attrs.paginationId)(scope) || attrs.paginationId || DEFAULT_ID;
  65. paginationService.registerInstance(paginationId);
  66. var repeatExpression = getRepeatExpression(expression, paginationId);
  67. addNgRepeatToElement(element, attrs, repeatExpression);
  68. removeTemporaryAttributes(element);
  69. var compiled = $compile(element);
  70. var currentPageGetter = makeCurrentPageGetterFn(scope, attrs, paginationId);
  71. paginationService.setCurrentPageParser(paginationId, currentPageGetter, scope);
  72. if (typeof attrs.totalItems !== 'undefined') {
  73. paginationService.setAsyncModeTrue(paginationId);
  74. scope.$watch(function() {
  75. return $parse(attrs.totalItems)(scope);
  76. }, function (result) {
  77. if (0 <= result) {
  78. paginationService.setCollectionLength(paginationId, result);
  79. }
  80. });
  81. } else {
  82. scope.$watchCollection(function() {
  83. return collectionGetter(scope);
  84. }, function(collection) {
  85. if (collection) {
  86. paginationService.setCollectionLength(paginationId, collection.length);
  87. }
  88. });
  89. }
  90. // Delegate to the link function returned by the new compilation of the ng-repeat
  91. compiled(scope);
  92. };
  93. }
  94. /**
  95. * If a pagination id has been specified, we need to check that it is present as the second argument passed to
  96. * the itemsPerPage filter. If it is not there, we add it and return the modified expression.
  97. *
  98. * @param expression
  99. * @param paginationId
  100. * @returns {*}
  101. */
  102. function getRepeatExpression(expression, paginationId) {
  103. var repeatExpression,
  104. idDefinedInFilter = !!expression.match(/(\|\s*itemsPerPage\s*:[^|]*:[^|]*)/);
  105. if (paginationId !== DEFAULT_ID && !idDefinedInFilter) {
  106. repeatExpression = expression.replace(/(\|\s*itemsPerPage\s*:[^|]*)/, "$1 : '" + paginationId + "'");
  107. } else {
  108. repeatExpression = expression;
  109. }
  110. return repeatExpression;
  111. }
  112. /**
  113. * Adds the ng-repeat directive to the element. In the case of multi-element (-start, -end) it adds the
  114. * appropriate multi-element ng-repeat to the first and last element in the range.
  115. * @param element
  116. * @param attrs
  117. * @param repeatExpression
  118. */
  119. function addNgRepeatToElement(element, attrs, repeatExpression) {
  120. if (element[0].hasAttribute('dir-paginate-start') || element[0].hasAttribute('data-dir-paginate-start')) {
  121. // using multiElement mode (dir-paginate-start, dir-paginate-end)
  122. attrs.$set('ngRepeatStart', repeatExpression);
  123. element.eq(element.length - 1).attr('ng-repeat-end', true);
  124. } else {
  125. attrs.$set('ngRepeat', repeatExpression);
  126. }
  127. }
  128. /**
  129. * Adds the dir-paginate-no-compile directive to each element in the tElement range.
  130. * @param tElement
  131. */
  132. function addNoCompileAttributes(tElement) {
  133. angular.forEach(tElement, function(el) {
  134. if (el.nodeType === Node.ELEMENT_NODE) {
  135. angular.element(el).attr('dir-paginate-no-compile', true);
  136. }
  137. });
  138. }
  139. /**
  140. * Removes the variations on dir-paginate (data-, -start, -end) and the dir-paginate-no-compile directives.
  141. * @param element
  142. */
  143. function removeTemporaryAttributes(element) {
  144. angular.forEach(element, function(el) {
  145. if (el.nodeType === Node.ELEMENT_NODE) {
  146. angular.element(el).removeAttr('dir-paginate-no-compile');
  147. }
  148. });
  149. element.eq(0).removeAttr('dir-paginate-start').removeAttr('dir-paginate').removeAttr('data-dir-paginate-start').removeAttr('data-dir-paginate');
  150. element.eq(element.length - 1).removeAttr('dir-paginate-end').removeAttr('data-dir-paginate-end');
  151. }
  152. /**
  153. * Creates a getter function for the current-page attribute, using the expression provided or a default value if
  154. * no current-page expression was specified.
  155. *
  156. * @param scope
  157. * @param attrs
  158. * @param paginationId
  159. * @returns {*}
  160. */
  161. function makeCurrentPageGetterFn(scope, attrs, paginationId) {
  162. var currentPageGetter;
  163. if (attrs.currentPage) {
  164. currentPageGetter = $parse(attrs.currentPage);
  165. } else {
  166. // if the current-page attribute was not set, we'll make our own
  167. var defaultCurrentPage = paginationId + '__currentPage';
  168. scope[defaultCurrentPage] = 1;
  169. currentPageGetter = $parse(defaultCurrentPage);
  170. }
  171. return currentPageGetter;
  172. }
  173. }
  174. /**
  175. * This is a helper directive that allows correct compilation when in multi-element mode (ie dir-paginate-start, dir-paginate-end).
  176. * It is dynamically added to all elements in the dir-paginate compile function, and it prevents further compilation of
  177. * any inner directives. It is then removed in the link function, and all inner directives are then manually compiled.
  178. */
  179. function noCompileDirective() {
  180. return {
  181. priority: 5000,
  182. terminal: true
  183. };
  184. }
  185. function dirPaginationControlsTemplateInstaller($templateCache) {
  186. $templateCache.put('angularUtils.directives.dirPagination.template', '<ul class="pagination" ng-if="1 < pages.length"><li ng-if="boundaryLinks" ng-class="{ disabled : pagination.current == 1 }"><a href="" ng-click="setCurrent(1)">&laquo;</a></li><li ng-if="directionLinks" ng-class="{ disabled : pagination.current == 1 }"><a href="" ng-click="setCurrent(pagination.current - 1)">&lsaquo;</a></li><li ng-repeat="pageNumber in pages track by $index" ng-class="{ active : pagination.current == pageNumber, disabled : pageNumber == \'...\' }"><a href="" ng-click="setCurrent(pageNumber)">{{ pageNumber }}</a></li><li ng-if="directionLinks" ng-class="{ disabled : pagination.current == pagination.last }"><a href="" ng-click="setCurrent(pagination.current + 1)">&rsaquo;</a></li><li ng-if="boundaryLinks" ng-class="{ disabled : pagination.current == pagination.last }"><a href="" ng-click="setCurrent(pagination.last)">&raquo;</a></li></ul>');
  187. }
  188. function dirPaginationControlsDirective(paginationService, paginationTemplate) {
  189. var numberRegex = /^\d+$/;
  190. return {
  191. restrict: 'AE',
  192. templateUrl: function(elem, attrs) {
  193. return attrs.templateUrl || paginationTemplate.getPath();
  194. },
  195. scope: {
  196. maxSize: '=?',
  197. onPageChange: '&?',
  198. paginationId: '=?'
  199. },
  200. link: dirPaginationControlsLinkFn
  201. };
  202. function dirPaginationControlsLinkFn(scope, element, attrs) {
  203. // rawId is the un-interpolated value of the pagination-id attribute. This is only important when the corresponding dir-paginate directive has
  204. // not yet been linked (e.g. if it is inside an ng-if block), and in that case it prevents this controls directive from assuming that there is
  205. // no corresponding dir-paginate directive and wrongly throwing an exception.
  206. var rawId = attrs.paginationId || DEFAULT_ID;
  207. var paginationId = scope.paginationId || attrs.paginationId || DEFAULT_ID;
  208. if (!paginationService.isRegistered(paginationId) && !paginationService.isRegistered(rawId)) {
  209. var idMessage = (paginationId !== DEFAULT_ID) ? ' (id: ' + paginationId + ') ' : ' ';
  210. throw 'pagination directive: the pagination controls' + idMessage + 'cannot be used without the corresponding pagination directive.';
  211. }
  212. if (!scope.maxSize) { scope.maxSize = 9; }
  213. scope.directionLinks = angular.isDefined(attrs.directionLinks) ? scope.$parent.$eval(attrs.directionLinks) : true;
  214. scope.boundaryLinks = angular.isDefined(attrs.boundaryLinks) ? scope.$parent.$eval(attrs.boundaryLinks) : false;
  215. var paginationRange = Math.max(scope.maxSize, 5);
  216. scope.pages = [];
  217. scope.pagination = {
  218. last: 1,
  219. current: 1
  220. };
  221. scope.range = {
  222. lower: 1,
  223. upper: 1,
  224. total: 1
  225. };
  226. scope.$watch(function() {
  227. return (paginationService.getCollectionLength(paginationId) + 1) * paginationService.getItemsPerPage(paginationId);
  228. }, function(length) {
  229. if (0 < length) {
  230. generatePagination();
  231. }
  232. });
  233. scope.$watch(function() {
  234. return (paginationService.getItemsPerPage(paginationId));
  235. }, function(current, previous) {
  236. if (current != previous && typeof previous !== 'undefined') {
  237. goToPage(scope.pagination.current);
  238. }
  239. });
  240. scope.$watch(function() {
  241. return paginationService.getCurrentPage(paginationId);
  242. }, function(currentPage, previousPage) {
  243. if (currentPage != previousPage) {
  244. goToPage(currentPage);
  245. }
  246. });
  247. scope.setCurrent = function(num) {
  248. if (isValidPageNumber(num)) {
  249. num = parseInt(num, 10);
  250. paginationService.setCurrentPage(paginationId, num);
  251. }
  252. };
  253. function goToPage(num) {
  254. if (isValidPageNumber(num)) {
  255. scope.pages = generatePagesArray(num, paginationService.getCollectionLength(paginationId), paginationService.getItemsPerPage(paginationId), paginationRange);
  256. scope.pagination.current = num;
  257. updateRangeValues();
  258. // if a callback has been set, then call it with the page number as an argument
  259. if (scope.onPageChange) {
  260. scope.onPageChange({ newPageNumber : num });
  261. }
  262. }
  263. }
  264. function generatePagination() {
  265. var page = parseInt(paginationService.getCurrentPage(paginationId)) || 1;
  266. scope.pages = generatePagesArray(page, paginationService.getCollectionLength(paginationId), paginationService.getItemsPerPage(paginationId), paginationRange);
  267. scope.pagination.current = page;
  268. scope.pagination.last = scope.pages[scope.pages.length - 1];
  269. if (scope.pagination.last < scope.pagination.current) {
  270. scope.setCurrent(scope.pagination.last);
  271. } else {
  272. updateRangeValues();
  273. }
  274. }
  275. /**
  276. * This function updates the values (lower, upper, total) of the `scope.range` object, which can be used in the pagination
  277. * template to display the current page range, e.g. "showing 21 - 40 of 144 results";
  278. */
  279. function updateRangeValues() {
  280. var currentPage = paginationService.getCurrentPage(paginationId),
  281. itemsPerPage = paginationService.getItemsPerPage(paginationId),
  282. totalItems = paginationService.getCollectionLength(paginationId);
  283. scope.range.lower = (currentPage - 1) * itemsPerPage + 1;
  284. scope.range.upper = Math.min(currentPage * itemsPerPage, totalItems);
  285. scope.range.total = totalItems;
  286. }
  287. function isValidPageNumber(num) {
  288. return (numberRegex.test(num) && (0 < num && num <= scope.pagination.last));
  289. }
  290. }
  291. /**
  292. * Generate an array of page numbers (or the '...' string) which is used in an ng-repeat to generate the
  293. * links used in pagination
  294. *
  295. * @param currentPage
  296. * @param rowsPerPage
  297. * @param paginationRange
  298. * @param collectionLength
  299. * @returns {Array}
  300. */
  301. function generatePagesArray(currentPage, collectionLength, rowsPerPage, paginationRange) {
  302. var pages = [];
  303. var totalPages = Math.ceil(collectionLength / rowsPerPage);
  304. var halfWay = Math.ceil(paginationRange / 2);
  305. var position;
  306. if (currentPage <= halfWay) {
  307. position = 'start';
  308. } else if (totalPages - halfWay < currentPage) {
  309. position = 'end';
  310. } else {
  311. position = 'middle';
  312. }
  313. var ellipsesNeeded = paginationRange < totalPages;
  314. var i = 1;
  315. while (i <= totalPages && i <= paginationRange) {
  316. var pageNumber = calculatePageNumber(i, currentPage, paginationRange, totalPages);
  317. var openingEllipsesNeeded = (i === 2 && (position === 'middle' || position === 'end'));
  318. var closingEllipsesNeeded = (i === paginationRange - 1 && (position === 'middle' || position === 'start'));
  319. if (ellipsesNeeded && (openingEllipsesNeeded || closingEllipsesNeeded)) {
  320. pages.push('...');
  321. } else {
  322. pages.push(pageNumber);
  323. }
  324. i ++;
  325. }
  326. return pages;
  327. }
  328. /**
  329. * Given the position in the sequence of pagination links [i], figure out what page number corresponds to that position.
  330. *
  331. * @param i
  332. * @param currentPage
  333. * @param paginationRange
  334. * @param totalPages
  335. * @returns {*}
  336. */
  337. function calculatePageNumber(i, currentPage, paginationRange, totalPages) {
  338. var halfWay = Math.ceil(paginationRange/2);
  339. if (i === paginationRange) {
  340. return totalPages;
  341. } else if (i === 1) {
  342. return i;
  343. } else if (paginationRange < totalPages) {
  344. if (totalPages - halfWay < currentPage) {
  345. return totalPages - paginationRange + i;
  346. } else if (halfWay < currentPage) {
  347. return currentPage - halfWay + i;
  348. } else {
  349. return i;
  350. }
  351. } else {
  352. return i;
  353. }
  354. }
  355. }
  356. /**
  357. * This filter slices the collection into pages based on the current page number and number of items per page.
  358. * @param paginationService
  359. * @returns {Function}
  360. */
  361. function itemsPerPageFilter(paginationService) {
  362. return function(collection, itemsPerPage, paginationId) {
  363. if (typeof (paginationId) === 'undefined') {
  364. paginationId = DEFAULT_ID;
  365. }
  366. if (!paginationService.isRegistered(paginationId)) {
  367. throw 'pagination directive: the itemsPerPage id argument (id: ' + paginationId + ') does not match a registered pagination-id.';
  368. }
  369. var end;
  370. var start;
  371. if (collection instanceof Array) {
  372. itemsPerPage = parseInt(itemsPerPage) || 9999999999;
  373. if (paginationService.isAsyncMode(paginationId)) {
  374. start = 0;
  375. } else {
  376. start = (paginationService.getCurrentPage(paginationId) - 1) * itemsPerPage;
  377. }
  378. end = start + itemsPerPage;
  379. paginationService.setItemsPerPage(paginationId, itemsPerPage);
  380. return collection.slice(start, end);
  381. } else {
  382. return collection;
  383. }
  384. };
  385. }
  386. /**
  387. * This service allows the various parts of the module to communicate and stay in sync.
  388. */
  389. function paginationService() {
  390. var instances = {};
  391. var lastRegisteredInstance;
  392. this.registerInstance = function(instanceId) {
  393. if (typeof instances[instanceId] === 'undefined') {
  394. instances[instanceId] = {
  395. asyncMode: false
  396. };
  397. lastRegisteredInstance = instanceId;
  398. }
  399. };
  400. this.isRegistered = function(instanceId) {
  401. return (typeof instances[instanceId] !== 'undefined');
  402. };
  403. this.getLastInstanceId = function() {
  404. return lastRegisteredInstance;
  405. };
  406. this.setCurrentPageParser = function(instanceId, val, scope) {
  407. instances[instanceId].currentPageParser = val;
  408. instances[instanceId].context = scope;
  409. };
  410. this.setCurrentPage = function(instanceId, val) {
  411. instances[instanceId].currentPageParser.assign(instances[instanceId].context, val);
  412. };
  413. this.getCurrentPage = function(instanceId) {
  414. var parser = instances[instanceId].currentPageParser;
  415. return parser ? parser(instances[instanceId].context) : 1;
  416. };
  417. this.setItemsPerPage = function(instanceId, val) {
  418. instances[instanceId].itemsPerPage = val;
  419. };
  420. this.getItemsPerPage = function(instanceId) {
  421. return instances[instanceId].itemsPerPage;
  422. };
  423. this.setCollectionLength = function(instanceId, val) {
  424. instances[instanceId].collectionLength = val;
  425. };
  426. this.getCollectionLength = function(instanceId) {
  427. return instances[instanceId].collectionLength;
  428. };
  429. this.setAsyncModeTrue = function(instanceId) {
  430. instances[instanceId].asyncMode = true;
  431. };
  432. this.isAsyncMode = function(instanceId) {
  433. return instances[instanceId].asyncMode;
  434. };
  435. }
  436. /**
  437. * This provider allows global configuration of the template path used by the dir-pagination-controls directive.
  438. */
  439. function paginationTemplateProvider() {
  440. var templatePath = 'angularUtils.directives.dirPagination.template';
  441. this.setPath = function(path) {
  442. templatePath = path;
  443. };
  444. this.$get = function() {
  445. return {
  446. getPath: function() {
  447. return templatePath;
  448. }
  449. };
  450. };
  451. }
  452. })();