ng-table.js 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518
  1. (function(angular, factory) {
  2. 'use strict';
  3. if (typeof define === 'function' && define.amd) {
  4. define(['angular'], function(angular) {
  5. return factory(angular);
  6. });
  7. } else {
  8. return factory(angular);
  9. }
  10. }(window.angular || null, function(angular) {
  11. 'use strict';
  12. /**
  13. * ngTable: Table + Angular JS
  14. *
  15. * @author Vitalii Savchuk <esvit666@gmail.com>
  16. * @url https://github.com/esvit/ng-table/
  17. * @license New BSD License <http://creativecommons.org/licenses/BSD/>
  18. */
  19. /**
  20. * @ngdoc module
  21. * @name ngTable
  22. * @description ngTable: Table + Angular JS
  23. * @example
  24. <doc:example>
  25. <doc:source>
  26. <script>
  27. var app = angular.module('myApp', ['ngTable']);
  28. app.controller('MyCtrl', function($scope) {
  29. $scope.users = [
  30. {name: "Moroni", age: 50},
  31. {name: "Tiancum", age: 43},
  32. {name: "Jacob", age: 27},
  33. {name: "Nephi", age: 29},
  34. {name: "Enos", age: 34}
  35. ];
  36. });
  37. </script>
  38. <table ng-table class="table">
  39. <tr ng-repeat="user in users">
  40. <td data-title="'Name'">{{user.name}}</td>
  41. <td data-title="'Age'">{{user.age}}</td>
  42. </tr>
  43. </table>
  44. </doc:source>
  45. </doc:example>
  46. */
  47. var app = angular.module('ngTable', []);
  48. /**
  49. * ngTable: Table + Angular JS
  50. *
  51. * @author Vitalii Savchuk <esvit666@gmail.com>
  52. * @url https://github.com/esvit/ng-table/
  53. * @license New BSD License <http://creativecommons.org/licenses/BSD/>
  54. */
  55. (function(){
  56. 'use strict';
  57. angular.module('ngTable')
  58. .factory('ngTableEventsChannel', ngTableEventsChannel);
  59. ngTableEventsChannel.$inject = ['$rootScope'];
  60. /**
  61. * @ngdoc service
  62. * @name ngTableEventsChannel
  63. * @description strongly typed pub/sub for `NgTableParams`
  64. *
  65. * Supported events:
  66. *
  67. * * afterCreated - raised when a new instance of `NgTableParams` has finished being constructed
  68. * * afterReloadData - raised when the `reload` event has finished loading new data
  69. * * datasetChanged - raised when `settings` receives a new data array
  70. * * pagesChanged - raised when a new pages array has been generated
  71. */
  72. function ngTableEventsChannel($rootScope){
  73. var events = {};
  74. events = addChangeEvent('afterCreated', events);
  75. events = addChangeEvent('afterReloadData', events);
  76. events = addChangeEvent('datasetChanged', events);
  77. events = addChangeEvent('pagesChanged', events);
  78. return events;
  79. //////////
  80. function addChangeEvent(eventName, target){
  81. var fnName = eventName.charAt(0).toUpperCase() + eventName.substring(1);
  82. var event = {};
  83. event['on' + fnName] = createEventSubscriptionFn(eventName);
  84. event['publish' + fnName] = createPublishEventFn(eventName);
  85. return angular.extend(target, event);
  86. }
  87. function createEventSubscriptionFn(eventName){
  88. return function subscription(handler/*[, eventSelector or $scope][, eventSelector]*/){
  89. var eventSelector = angular.identity;
  90. var scope = $rootScope;
  91. if (arguments.length === 2){
  92. if (angular.isFunction(arguments[1].$new)) {
  93. scope = arguments[1];
  94. } else {
  95. eventSelector = arguments[1]
  96. }
  97. } else if (arguments.length > 2){
  98. scope = arguments[1];
  99. eventSelector = arguments[2];
  100. }
  101. // shorthand for subscriber to only receive events from a specific publisher instance
  102. if (angular.isObject(eventSelector)) {
  103. var requiredPublisher = eventSelector;
  104. eventSelector = function(publisher){
  105. return publisher === requiredPublisher;
  106. }
  107. }
  108. return scope.$on('ngTable:' + eventName, function(event, params/*, ...args*/){
  109. // don't send events published by the internal NgTableParams created by ngTableController
  110. if (params.isNullInstance) return;
  111. var eventArgs = rest(arguments, 2);
  112. var fnArgs = [params].concat(eventArgs);
  113. if (eventSelector.apply(this, fnArgs)){
  114. handler.apply(this, fnArgs);
  115. }
  116. });
  117. }
  118. }
  119. function createPublishEventFn(eventName){
  120. return function publish(/*args*/){
  121. var fnArgs = ['ngTable:' + eventName].concat(Array.prototype.slice.call(arguments));
  122. $rootScope.$broadcast.apply($rootScope, fnArgs);
  123. }
  124. }
  125. function rest(array, n) {
  126. return Array.prototype.slice.call(array, n == null ? 1 : n);
  127. }
  128. }
  129. })();
  130. /**
  131. * ngTable: Table + Angular JS
  132. *
  133. * @author Vitalii Savchuk <esvit666@gmail.com>
  134. * @url https://github.com/esvit/ng-table/
  135. * @license New BSD License <http://creativecommons.org/licenses/BSD/>
  136. */
  137. (function(){
  138. 'use strict';
  139. angular.module('ngTable')
  140. .provider('ngTableFilterConfig', ngTableFilterConfigProvider);
  141. ngTableFilterConfigProvider.$inject = [];
  142. function ngTableFilterConfigProvider(){
  143. var config;
  144. var defaultConfig = {
  145. defaultBaseUrl: 'ng-table/filters/',
  146. defaultExt: '.html',
  147. aliasUrls: {}
  148. };
  149. this.$get = ngTableFilterConfig;
  150. this.resetConfigs = resetConfigs;
  151. this.setConfig = setConfig;
  152. init();
  153. /////////
  154. function init(){
  155. resetConfigs();
  156. }
  157. function resetConfigs(){
  158. config = defaultConfig;
  159. }
  160. function setConfig(customConfig){
  161. var mergeConfig = angular.extend({}, config, customConfig);
  162. mergeConfig.aliasUrls = angular.extend({}, config.aliasUrls, customConfig.aliasUrls);
  163. config = mergeConfig;
  164. }
  165. /////////
  166. ngTableFilterConfig.$inject = [];
  167. function ngTableFilterConfig(){
  168. var publicConfig;
  169. var service = {
  170. config: publicConfig,
  171. getTemplateUrl: getTemplateUrl,
  172. getUrlForAlias: getUrlForAlias
  173. };
  174. Object.defineProperty(service, "config", {
  175. get: function(){
  176. return publicConfig = publicConfig || angular.copy(config);
  177. },
  178. enumerable: true
  179. });
  180. return service;
  181. /////////
  182. function getTemplateUrl(filterValue, filterKey){
  183. if (filterValue.indexOf('/') !== -1){
  184. return filterValue;
  185. }
  186. return service.getUrlForAlias(filterValue, filterKey);
  187. }
  188. function getUrlForAlias(aliasName/*, filterKey*/){
  189. return config.aliasUrls[aliasName] || config.defaultBaseUrl + aliasName + config.defaultExt;
  190. }
  191. }
  192. }
  193. })();
  194. /**
  195. * ngTable: Table + Angular JS
  196. *
  197. * @author Vitalii Savchuk <esvit666@gmail.com>
  198. * @url https://github.com/esvit/ng-table/
  199. * @license New BSD License <http://creativecommons.org/licenses/BSD/>
  200. */
  201. (function(){
  202. 'use strict';
  203. angular.module('ngTable')
  204. .provider('ngTableDefaultGetData', ngTableDefaultGetDataProvider);
  205. ngTableDefaultGetDataProvider.$inject = [];
  206. /**
  207. * @ngdoc provider
  208. * @name ngTableDefaultGetDataProvider
  209. * @description Allows for the configuration of the {@link ngTable.ngTableDefaultGetData ngTableDefaultGetData}
  210. * service.
  211. *
  212. * Set filterFilterName to the name of a angular filter that knows how to take `NgTableParams.filter()`
  213. * to restrict an array of data.
  214. *
  215. * Set sortingFilterName to the name of a angular filter that knows how to take `NgTableParams.orderBy()`
  216. * to sort an array of data.
  217. *
  218. * Out of the box the `ngTableDefaultGetData` service will be configured to use the angular `filter` and `orderBy`
  219. * filters respectively
  220. */
  221. function ngTableDefaultGetDataProvider(){
  222. var provider = this;
  223. provider.$get = ngTableDefaultGetData;
  224. provider.filterFilterName = 'filter';
  225. provider.sortingFilterName = 'orderBy';
  226. ///////////
  227. ngTableDefaultGetData.$inject = ['$filter'];
  228. /**
  229. * @ngdoc service
  230. * @name ngTableDefaultGetData
  231. * @description A default implementation of the getData function that will apply the `filter`, `orderBy` and
  232. * paging values from the `NgTableParams` instance supplied to the data array supplied.
  233. *
  234. * The outcome will be to return the resulting array and to assign the total item count after filtering
  235. * to the `total` of the `NgTableParams` instance supplied
  236. */
  237. function ngTableDefaultGetData($filter) {
  238. return getData;
  239. function getData(data, params) {
  240. if (data == null){
  241. return [];
  242. }
  243. var fData = params.hasFilter() ? $filter(provider.filterFilterName)(data, params.filter(true)) : data;
  244. var orderBy = params.orderBy();
  245. var orderedData = orderBy.length ? $filter(provider.sortingFilterName)(fData, orderBy) : fData;
  246. var pagedData = orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count());
  247. params.total(orderedData.length); // set total for recalc pagination
  248. return pagedData;
  249. }
  250. }
  251. }
  252. })();
  253. /**
  254. * ngTable: Table + Angular JS
  255. *
  256. * @author Vitalii Savchuk <esvit666@gmail.com>
  257. * @url https://github.com/esvit/ng-table/
  258. * @license New BSD License <http://creativecommons.org/licenses/BSD/>
  259. */
  260. (function(){
  261. 'use strict';
  262. // todo: remove shim after an acceptable depreciation period
  263. angular.module('ngTable')
  264. .factory('ngTableGetDataBcShim', ngTableGetDataBcShim);
  265. ngTableGetDataBcShim.$inject = ['$q'];
  266. function ngTableGetDataBcShim($q){
  267. return createWrapper;
  268. function createWrapper(getDataFn){
  269. return function getDataShim(/*args*/){
  270. var $defer = $q.defer();
  271. var pData = getDataFn.apply(this, [$defer].concat(Array.prototype.slice.call(arguments)));
  272. if (!pData) {
  273. // If getData resolved the $defer, and didn't promise us data,
  274. // create a promise from the $defer. We need to return a promise.
  275. pData = $defer.promise;
  276. }
  277. return pData;
  278. }
  279. }
  280. }
  281. })();
  282. /**
  283. * ngTable: Table + Angular JS
  284. *
  285. * @author Vitalii Savchuk <esvit666@gmail.com>
  286. * @url https://github.com/esvit/ng-table/
  287. * @license New BSD License <http://creativecommons.org/licenses/BSD/>
  288. */
  289. /**
  290. * @ngdoc object
  291. * @name ngTableDefaultParams
  292. * @module ngTable
  293. * @description Default Parameters for ngTable
  294. */
  295. app.value('ngTableDefaults', {
  296. params: {},
  297. settings: {}
  298. });
  299. /**
  300. * @ngdoc service
  301. * @name NgTableParams
  302. * @module ngTable
  303. * @description Parameters manager for ngTable
  304. */
  305. app.factory('NgTableParams', ['$q', '$log', 'ngTableDefaults', 'ngTableGetDataBcShim', 'ngTableDefaultGetData', 'ngTableEventsChannel', function($q, $log, ngTableDefaults, ngTableGetDataBcShim, ngTableDefaultGetData, ngTableEventsChannel) {
  306. var isNumber = function(n) {
  307. return !isNaN(parseFloat(n)) && isFinite(n);
  308. };
  309. var NgTableParams = function(baseParameters, baseSettings) {
  310. // the ngTableController "needs" to create a dummy/null instance and it's important to know whether an instance
  311. // is one of these
  312. if (typeof baseParameters === "boolean"){
  313. this.isNullInstance = true;
  314. }
  315. var self = this,
  316. committedParams,
  317. isCommittedDataset = false,
  318. log = function() {
  319. if (settings.debugMode && $log.debug) {
  320. $log.debug.apply(this, arguments);
  321. }
  322. };
  323. this.data = [];
  324. /**
  325. * @ngdoc method
  326. * @name NgTableParams#parameters
  327. * @description Set new parameters or get current parameters
  328. *
  329. * @param {string} newParameters New parameters
  330. * @param {string} parseParamsFromUrl Flag if parse parameters like in url
  331. * @returns {Object} Current parameters or `this`
  332. */
  333. this.parameters = function(newParameters, parseParamsFromUrl) {
  334. parseParamsFromUrl = parseParamsFromUrl || false;
  335. if (angular.isDefined(newParameters)) {
  336. for (var key in newParameters) {
  337. var value = newParameters[key];
  338. if (parseParamsFromUrl && key.indexOf('[') >= 0) {
  339. var keys = key.split(/\[(.*)\]/).reverse()
  340. var lastKey = '';
  341. for (var i = 0, len = keys.length; i < len; i++) {
  342. var name = keys[i];
  343. if (name !== '') {
  344. var v = value;
  345. value = {};
  346. value[lastKey = name] = (isNumber(v) ? parseFloat(v) : v);
  347. }
  348. }
  349. if (lastKey === 'sorting') {
  350. params[lastKey] = {};
  351. }
  352. params[lastKey] = angular.extend(params[lastKey] || {}, value[lastKey]);
  353. } else {
  354. params[key] = (isNumber(newParameters[key]) ? parseFloat(newParameters[key]) : newParameters[key]);
  355. }
  356. }
  357. log('ngTable: set parameters', params);
  358. return this;
  359. }
  360. return params;
  361. };
  362. /**
  363. * @ngdoc method
  364. * @name NgTableParams#settings
  365. * @description Set new settings for table
  366. *
  367. * @param {string} newSettings New settings or undefined
  368. * @returns {Object} Current settings or `this`
  369. */
  370. this.settings = function(newSettings) {
  371. if (angular.isDefined(newSettings)) {
  372. if (angular.isArray(newSettings.data)) {
  373. //auto-set the total from passed in data
  374. newSettings.total = newSettings.data.length;
  375. }
  376. // todo: remove the backwards compatibility shim and the following two if blocks
  377. if (newSettings.getData && newSettings.getData.length > 1){
  378. // support the old getData($defer, params) api
  379. newSettings.getDataFnAdaptor = ngTableGetDataBcShim;
  380. }
  381. if (newSettings.getGroups && newSettings.getGroups.length > 2){
  382. // support the old getGroups($defer, grouping, params) api
  383. newSettings.getGroupsFnAdaptor = ngTableGetDataBcShim;
  384. }
  385. var originalDataset = settings.data;
  386. settings = angular.extend(settings, newSettings);
  387. // note: using != as want null and undefined to be treated the same
  388. var hasDatasetChanged = newSettings.hasOwnProperty('data') && (newSettings.data != originalDataset);
  389. if (hasDatasetChanged) {
  390. if (isCommittedDataset){
  391. this.page(1); // reset page as a new dataset has been supplied
  392. }
  393. isCommittedDataset = false;
  394. ngTableEventsChannel.publishDatasetChanged(this, newSettings.data, originalDataset);
  395. }
  396. log('ngTable: set settings', settings);
  397. return this;
  398. }
  399. return settings;
  400. };
  401. /**
  402. * @ngdoc method
  403. * @name NgTableParams#page
  404. * @description If parameter page not set return current page else set current page
  405. *
  406. * @param {string} page Page number
  407. * @returns {Object|Number} Current page or `this`
  408. */
  409. this.page = function(page) {
  410. return angular.isDefined(page) ? this.parameters({
  411. 'page': page
  412. }) : params.page;
  413. };
  414. /**
  415. * @ngdoc method
  416. * @name NgTableParams#total
  417. * @description If parameter total not set return current quantity else set quantity
  418. *
  419. * @param {string} total Total quantity of items
  420. * @returns {Object|Number} Current page or `this`
  421. */
  422. this.total = function(total) {
  423. return angular.isDefined(total) ? this.settings({
  424. 'total': total
  425. }) : settings.total;
  426. };
  427. /**
  428. * @ngdoc method
  429. * @name NgTableParams#count
  430. * @description If parameter count not set return current count per page else set count per page
  431. *
  432. * @param {string} count Count per number
  433. * @returns {Object|Number} Count per page or `this`
  434. */
  435. this.count = function(count) {
  436. // reset to first page because can be blank page
  437. return angular.isDefined(count) ? this.parameters({
  438. 'count': count,
  439. 'page': 1
  440. }) : params.count;
  441. };
  442. /**
  443. * @ngdoc method
  444. * @name NgTableParams#filter
  445. * @description If 'filter' parameter not set return current filter else set current filter
  446. *
  447. * Note: when assigning a new filter, {@link NgTableParams#page page} will be set to 1
  448. *
  449. * @param {Object|Boolean} filter 'object': new filter to assign or
  450. * 'true': to return the current filter minus any insignificant values (null, undefined and empty string); or
  451. * 'falsey': to return the current filter "as is"
  452. * @returns {Object} Current filter or `this`
  453. */
  454. this.filter = function(filter) {
  455. if (angular.isDefined(filter) && angular.isObject(filter)) {
  456. return this.parameters({
  457. 'filter': filter,
  458. 'page': 1
  459. });
  460. } else if (filter === true){
  461. var keys = Object.keys(params.filter);
  462. var significantFilter = {};
  463. for (var i=0; i < keys.length; i++){
  464. var filterValue = params.filter[keys[i]];
  465. if (filterValue != null && filterValue !== '') {
  466. significantFilter[keys[i]] = filterValue;
  467. }
  468. }
  469. return significantFilter;
  470. } else {
  471. return params.filter;
  472. }
  473. };
  474. /**
  475. * @ngdoc method
  476. * @name NgTableParams#sorting
  477. * @description If 'sorting' parameter is not set, return current sorting. Otherwise set current sorting.
  478. *
  479. * @param {string} sorting New sorting
  480. * @returns {Object} Current sorting or `this`
  481. */
  482. this.sorting = function(sorting) {
  483. if (arguments.length == 2) {
  484. var sortArray = {};
  485. sortArray[sorting] = arguments[1];
  486. this.parameters({
  487. 'sorting': sortArray
  488. });
  489. return this;
  490. }
  491. return angular.isDefined(sorting) ? this.parameters({
  492. 'sorting': sorting
  493. }) : params.sorting;
  494. };
  495. /**
  496. * @ngdoc method
  497. * @name NgTableParams#isSortBy
  498. * @description Checks sort field
  499. *
  500. * @param {string} field Field name
  501. * @param {string} direction Optional direction of sorting ('asc' or 'desc')
  502. * @returns {Array} Return true if field sorted by direction
  503. */
  504. this.isSortBy = function(field, direction) {
  505. if(direction !== undefined) {
  506. return angular.isDefined(params.sorting[field]) && params.sorting[field] == direction;
  507. } else {
  508. return angular.isDefined(params.sorting[field]);
  509. }
  510. };
  511. /**
  512. * @ngdoc method
  513. * @name NgTableParams#orderBy
  514. * @description Return object of sorting parameters for angular filter
  515. *
  516. * @returns {Array} Array like: [ '-name', '+age' ]
  517. */
  518. this.orderBy = function() {
  519. var sorting = [];
  520. for (var column in params.sorting) {
  521. sorting.push((params.sorting[column] === "asc" ? "+" : "-") + column);
  522. }
  523. return sorting;
  524. };
  525. /**
  526. * @ngdoc method
  527. * @name NgTableParams#getData
  528. * @description Called when updated some of parameters for get new data
  529. *
  530. * @param {Object} params New parameters
  531. */
  532. this.getData = function(params) {
  533. // note: this === settings
  534. return ngTableDefaultGetData(this.data, params);
  535. };
  536. /**
  537. * @ngdoc method
  538. * @name NgTableParams#getGroups
  539. * @description Return groups for table grouping
  540. */
  541. this.getGroups = function(column) {
  542. return runGetData().then(function(data) {
  543. var groups = {};
  544. angular.forEach(data, function(item) {
  545. var groupName = angular.isFunction(column) ? column(item) : item[column];
  546. groups[groupName] = groups[groupName] || {
  547. data: []
  548. };
  549. groups[groupName]['value'] = groupName;
  550. groups[groupName].data.push(item);
  551. });
  552. var result = [];
  553. for (var i in groups) {
  554. result.push(groups[i]);
  555. }
  556. log('ngTable: refresh groups', result);
  557. return result;
  558. });
  559. };
  560. /**
  561. * @ngdoc method
  562. * @name NgTableParams#generatePagesArray
  563. * @description Generate array of pages
  564. *
  565. * When no arguments supplied, the current parameter state of this `NgTableParams` instance will be used
  566. *
  567. * @param {boolean} currentPage which page must be active
  568. * @param {boolean} totalItems Total quantity of items
  569. * @param {boolean} pageSize Quantity of items on page
  570. * @param {number} maxBlocks Quantity of blocks for pagination
  571. * @returns {Array} Array of pages
  572. */
  573. this.generatePagesArray = function(currentPage, totalItems, pageSize, maxBlocks) {
  574. if (!arguments.length){
  575. currentPage = this.page();
  576. totalItems = this.total();
  577. pageSize = this.count();
  578. }
  579. var maxPage, maxPivotPages, minPage, numPages, pages;
  580. maxBlocks = maxBlocks && maxBlocks < 6 ? 6 : maxBlocks;
  581. pages = [];
  582. numPages = Math.ceil(totalItems / pageSize);
  583. if (numPages > 1) {
  584. pages.push({
  585. type: 'prev',
  586. number: Math.max(1, currentPage - 1),
  587. active: currentPage > 1
  588. });
  589. pages.push({
  590. type: 'first',
  591. number: 1,
  592. active: currentPage > 1,
  593. current: currentPage === 1
  594. });
  595. maxPivotPages = Math.round((settings.paginationMaxBlocks - settings.paginationMinBlocks) / 2);
  596. minPage = Math.max(2, currentPage - maxPivotPages);
  597. maxPage = Math.min(numPages - 1, currentPage + maxPivotPages * 2 - (currentPage - minPage));
  598. minPage = Math.max(2, minPage - (maxPivotPages * 2 - (maxPage - minPage)));
  599. var i = minPage;
  600. while (i <= maxPage) {
  601. if ((i === minPage && i !== 2) || (i === maxPage && i !== numPages - 1)) {
  602. pages.push({
  603. type: 'more',
  604. active: false
  605. });
  606. } else {
  607. pages.push({
  608. type: 'page',
  609. number: i,
  610. active: currentPage !== i,
  611. current: currentPage === i
  612. });
  613. }
  614. i++;
  615. }
  616. pages.push({
  617. type: 'last',
  618. number: numPages,
  619. active: currentPage !== numPages,
  620. current: currentPage === numPages
  621. });
  622. pages.push({
  623. type: 'next',
  624. number: Math.min(numPages, currentPage + 1),
  625. active: currentPage < numPages
  626. });
  627. }
  628. return pages;
  629. };
  630. /**
  631. * @ngdoc method
  632. * @name NgTableParams#isDataReloadRequired
  633. * @description Return true when a change to this `NgTableParams` instance should require the reload method
  634. * to be run so as to ensure the data presented to the user reflects the `NgTableParams`
  635. */
  636. this.isDataReloadRequired = function(){
  637. // note: using != as want to treat null and undefined the same
  638. return !isCommittedDataset || !angular.equals(params, committedParams);
  639. };
  640. /**
  641. * @ngdoc method
  642. * @name NgTableParams#hasFilter
  643. * @description Determines if NgTableParams#filter has significant filter value(s)
  644. * (any value except null, undefined, or empty string)
  645. * @returns {Boolean} true when NgTableParams#filter has at least one significant field value
  646. */
  647. this.hasFilter = function(){
  648. return Object.keys(this.filter(true)).length > 0;
  649. };
  650. /**
  651. * @ngdoc method
  652. * @name NgTableParams#hasFilterChanges
  653. * @description Return true when a change to `NgTableParams.filters`require the reload method
  654. * to be run so as to ensure the data presented to the user reflects these filters
  655. */
  656. this.hasFilterChanges = function(){
  657. return !angular.equals((params && params.filter), (committedParams && committedParams.filter));
  658. };
  659. /**
  660. * @ngdoc method
  661. * @name NgTableParams#url
  662. * @description Return groups for table grouping
  663. *
  664. * @param {boolean} asString flag indicates return array of string or object
  665. * @returns {Array} If asString = true will be return array of url string parameters else key-value object
  666. */
  667. this.url = function(asString) {
  668. asString = asString || false;
  669. var pairs = (asString ? [] : {});
  670. for (var key in params) {
  671. if (params.hasOwnProperty(key)) {
  672. var item = params[key],
  673. name = encodeURIComponent(key);
  674. if (typeof item === "object") {
  675. for (var subkey in item) {
  676. if (!angular.isUndefined(item[subkey]) && item[subkey] !== "") {
  677. var pname = name + "[" + encodeURIComponent(subkey) + "]";
  678. if (asString) {
  679. pairs.push(pname + "=" + item[subkey]);
  680. } else {
  681. pairs[pname] = item[subkey];
  682. }
  683. }
  684. }
  685. } else if (!angular.isFunction(item) && !angular.isUndefined(item) && item !== "") {
  686. if (asString) {
  687. pairs.push(name + "=" + encodeURIComponent(item));
  688. } else {
  689. pairs[name] = encodeURIComponent(item);
  690. }
  691. }
  692. }
  693. }
  694. return pairs;
  695. };
  696. /**
  697. * @ngdoc method
  698. * @name NgTableParams#reload
  699. * @description Reload table data
  700. */
  701. this.reload = function() {
  702. var self = this,
  703. pData = null;
  704. settings.$loading = true;
  705. committedParams = angular.copy(params);
  706. isCommittedDataset = true;
  707. if (settings.groupBy) {
  708. pData = runInterceptorPipeline(runGetGroups);
  709. } else {
  710. pData = runInterceptorPipeline(runGetData);
  711. }
  712. log('ngTable: reload data');
  713. var oldData = self.data;
  714. return pData.then(function(data) {
  715. settings.$loading = false;
  716. self.data = data;
  717. // note: I think it makes sense to publish this event even when data === oldData
  718. // subscribers can always set a filter to only receive the event when data !== oldData
  719. ngTableEventsChannel.publishAfterReloadData(self, data, oldData);
  720. self.reloadPages();
  721. // todo: remove after acceptable depreciation period
  722. if (settings.$scope) {
  723. settings.$scope.$emit('ngTableAfterReloadData');
  724. }
  725. return data;
  726. }).catch(function(reason){
  727. committedParams = null;
  728. isCommittedDataset = false;
  729. // "rethrow"
  730. return $q.reject(reason);
  731. });
  732. };
  733. this.reloadPages = (function() {
  734. var currentPages;
  735. return function(){
  736. var oldPages = currentPages;
  737. var newPages = self.generatePagesArray(self.page(), self.total(), self.count());
  738. if (!angular.equals(oldPages, newPages)){
  739. currentPages = newPages;
  740. ngTableEventsChannel.publishPagesChanged(this, newPages, oldPages);
  741. }
  742. }
  743. })();
  744. function runGetData(){
  745. var getDataFn = settings.getDataFnAdaptor(settings.getData);
  746. return $q.when(getDataFn.call(settings, self));
  747. }
  748. function runGetGroups(){
  749. var getGroupsFn = settings.getGroupsFnAdaptor(settings.getGroups);
  750. return $q.when(getGroupsFn.call(settings, settings.groupBy, self));
  751. }
  752. function runInterceptorPipeline(fetchFn){
  753. var interceptors = settings.interceptors || [];
  754. return interceptors.reduce(function(result, interceptor){
  755. var thenFn = (interceptor.response && interceptor.response.bind(interceptor)) || $q.when;
  756. var rejectFn = (interceptor.responseError && interceptor.responseError.bind(interceptor)) || $q.reject;
  757. return result.then(function(data){
  758. return thenFn(data, self);
  759. }, function(reason){
  760. return rejectFn(reason, self);
  761. });
  762. }, fetchFn());
  763. }
  764. var params = {
  765. page: 1,
  766. count: 1,
  767. filter: {},
  768. sorting: {},
  769. group: {},
  770. groupBy: null
  771. };
  772. angular.extend(params, ngTableDefaults.params);
  773. var settings = {
  774. // todo: remove $scope after acceptable depreciation period as no longer required
  775. $scope: null, // set by ngTable controller
  776. $loading: false,
  777. data: null, //allows data to be set when table is initialized
  778. total: 0,
  779. defaultSort: 'desc',
  780. filterDelay: 750,
  781. counts: [10, 25, 50, 100],
  782. interceptors: [],
  783. paginationMaxBlocks: 11,
  784. paginationMinBlocks: 5,
  785. sortingIndicator: 'span',
  786. getDataFnAdaptor: angular.identity,
  787. getGroupsFnAdaptor: angular.identity,
  788. getGroups: this.getGroups,
  789. getData: this.getData
  790. };
  791. this.settings(ngTableDefaults.settings);
  792. this.settings(baseSettings);
  793. this.parameters(baseParameters, true);
  794. ngTableEventsChannel.publishAfterCreated(this);
  795. return this;
  796. };
  797. return NgTableParams;
  798. }]);
  799. /**
  800. * @ngdoc service
  801. * @name ngTableParams
  802. * @description Backwards compatible shim for lowercase 'n' in NgTableParams
  803. */
  804. app.factory('ngTableParams', ['NgTableParams', function(NgTableParams) {
  805. return NgTableParams;
  806. }]);
  807. /**
  808. * ngTable: Table + Angular JS
  809. *
  810. * @author Vitalii Savchuk <esvit666@gmail.com>
  811. * @url https://github.com/esvit/ng-table/
  812. * @license New BSD License <http://creativecommons.org/licenses/BSD/>
  813. */
  814. (function(){
  815. 'use strict';
  816. angular.module('ngTable')
  817. .controller('ngTableFilterRowController', ngTableFilterRowController);
  818. ngTableFilterRowController.$inject = ['$scope', 'ngTableFilterConfig'];
  819. function ngTableFilterRowController($scope, ngTableFilterConfig){
  820. $scope.config = ngTableFilterConfig;
  821. }
  822. })();
  823. /**
  824. * ngTable: Table + Angular JS
  825. *
  826. * @author Vitalii Savchuk <esvit666@gmail.com>
  827. * @url https://github.com/esvit/ng-table/
  828. * @license New BSD License <http://creativecommons.org/licenses/BSD/>
  829. */
  830. (function(){
  831. 'use strict';
  832. angular.module('ngTable')
  833. .controller('ngTableSorterRowController', ngTableSorterRowController);
  834. ngTableSorterRowController.$inject = ['$scope'];
  835. function ngTableSorterRowController($scope){
  836. $scope.sortBy = sortBy;
  837. ///////////
  838. function sortBy($column, event) {
  839. var parsedSortable = $column.sortable && $column.sortable();
  840. if (!parsedSortable) {
  841. return;
  842. }
  843. var defaultSort = $scope.params.settings().defaultSort;
  844. var inverseSort = (defaultSort === 'asc' ? 'desc' : 'asc');
  845. var sorting = $scope.params.sorting() && $scope.params.sorting()[parsedSortable] && ($scope.params.sorting()[parsedSortable] === defaultSort);
  846. var sortingParams = (event.ctrlKey || event.metaKey) ? $scope.params.sorting() : {};
  847. sortingParams[parsedSortable] = (sorting ? inverseSort : defaultSort);
  848. $scope.params.parameters({
  849. sorting: sortingParams
  850. });
  851. }
  852. }
  853. })();
  854. /**
  855. * ngTable: Table + Angular JS
  856. *
  857. * @author Vitalii Savchuk <esvit666@gmail.com>
  858. * @url https://github.com/esvit/ng-table/
  859. * @license New BSD License <http://creativecommons.org/licenses/BSD/>
  860. */
  861. /**
  862. * @ngdoc object
  863. * @name ngTableController
  864. *
  865. * @description
  866. * Each {@link ngTable ngTable} directive creates an instance of `ngTableController`
  867. */
  868. app.controller('ngTableController', ['$scope', 'NgTableParams', '$timeout', '$parse', '$compile', '$attrs', '$element',
  869. 'ngTableColumn', 'ngTableEventsChannel',
  870. function($scope, NgTableParams, $timeout, $parse, $compile, $attrs, $element, ngTableColumn, ngTableEventsChannel) {
  871. var isFirstTimeLoad = true;
  872. $scope.$filterRow = {};
  873. $scope.$loading = false;
  874. // until such times as the directive uses an isolated scope, we need to ensure that the check for
  875. // the params field only consults the "own properties" of the $scope. This is to avoid seeing the params
  876. // field on a $scope higher up in the prototype chain
  877. if (!$scope.hasOwnProperty("params")) {
  878. $scope.params = new NgTableParams(true);
  879. }
  880. $scope.params.settings().$scope = $scope;
  881. var delayFilter = (function() {
  882. var timer = 0;
  883. return function(callback, ms) {
  884. $timeout.cancel(timer);
  885. timer = $timeout(callback, ms);
  886. };
  887. })();
  888. function onDataReloadStatusChange (newStatus/*, oldStatus*/) {
  889. if (!newStatus) {
  890. return;
  891. }
  892. $scope.params.settings().$scope = $scope;
  893. var currentParams = $scope.params;
  894. if (currentParams.hasFilterChanges()) {
  895. var applyFilter = function () {
  896. currentParams.page(1);
  897. currentParams.reload();
  898. };
  899. if (currentParams.settings().filterDelay) {
  900. delayFilter(applyFilter, currentParams.settings().filterDelay);
  901. } else {
  902. applyFilter();
  903. }
  904. } else {
  905. currentParams.reload();
  906. }
  907. }
  908. // watch for when a new NgTableParams is bound to the scope
  909. // CRITICAL: the watch must be for reference and NOT value equality; this is because NgTableParams maintains
  910. // the current data page as a field. Checking this for value equality would be terrible for performance
  911. // and potentially cause an error if the items in that array has circular references
  912. $scope.$watch('params', function(newParams, oldParams){
  913. if (newParams === oldParams || !newParams) {
  914. return;
  915. }
  916. newParams.reload();
  917. }, false);
  918. $scope.$watch('params.isDataReloadRequired()', onDataReloadStatusChange);
  919. this.compileDirectiveTemplates = function () {
  920. if (!$element.hasClass('ng-table')) {
  921. $scope.templates = {
  922. header: ($attrs.templateHeader ? $attrs.templateHeader : 'ng-table/header.html'),
  923. pagination: ($attrs.templatePagination ? $attrs.templatePagination : 'ng-table/pager.html')
  924. };
  925. $element.addClass('ng-table');
  926. var headerTemplate = null;
  927. // $element.find('> thead').length === 0 doesn't work on jqlite
  928. var theadFound = false;
  929. angular.forEach($element.children(), function(e) {
  930. if (e.tagName === 'THEAD') {
  931. theadFound = true;
  932. }
  933. });
  934. if (!theadFound) {
  935. headerTemplate = angular.element(document.createElement('thead')).attr('ng-include', 'templates.header');
  936. $element.prepend(headerTemplate);
  937. }
  938. var paginationTemplate = angular.element(document.createElement('div')).attr({
  939. 'ng-table-pagination': 'params',
  940. 'template-url': 'templates.pagination'
  941. });
  942. $element.after(paginationTemplate);
  943. if (headerTemplate) {
  944. $compile(headerTemplate)($scope);
  945. }
  946. $compile(paginationTemplate)($scope);
  947. }
  948. };
  949. this.loadFilterData = function ($columns) {
  950. angular.forEach($columns, function ($column) {
  951. var def;
  952. def = $column.filterData($scope, {
  953. $column: $column
  954. });
  955. if (!def) {
  956. delete $column.filterData;
  957. return;
  958. }
  959. // if we're working with a deferred object, let's wait for the promise
  960. if ((angular.isObject(def) && angular.isObject(def.promise))) {
  961. delete $column.filterData;
  962. return def.promise.then(function(data) {
  963. // our deferred can eventually return arrays, functions and objects
  964. if (!angular.isArray(data) && !angular.isFunction(data) && !angular.isObject(data)) {
  965. // if none of the above was found - we just want an empty array
  966. data = [];
  967. } else if (angular.isArray(data)) {
  968. data.unshift({
  969. title: '',
  970. id: ''
  971. });
  972. }
  973. $column.data = data;
  974. });
  975. }
  976. // otherwise, we just return what the user gave us. It could be a function, array, object, whatever
  977. else {
  978. return $column.data = def;
  979. }
  980. });
  981. };
  982. this.buildColumns = function (columns) {
  983. return columns.map(function(col){
  984. return ngTableColumn.buildColumn(col, $scope)
  985. })
  986. };
  987. this.parseNgTableDynamicExpr = function (attr) {
  988. if (!attr || attr.indexOf(" with ") > -1) {
  989. var parts = attr.split(/\s+with\s+/);
  990. return {
  991. tableParams: parts[0],
  992. columns: parts[1]
  993. };
  994. } else {
  995. throw new Error('Parse error (expected example: ng-table-dynamic=\'tableParams with cols\')');
  996. }
  997. };
  998. this.setupBindingsToInternalScope = function(tableParamsExpr){
  999. // note: this we're setting up watches to simulate angular's isolated scope bindings
  1000. // note: is REALLY important to watch for a change to the ngTableParams *reference* rather than
  1001. // $watch for value equivalence. This is because ngTableParams references the current page of data as
  1002. // a field and it's important not to watch this
  1003. var tableParamsGetter = $parse(tableParamsExpr);
  1004. $scope.$watch(tableParamsGetter, (function (params) {
  1005. if (angular.isUndefined(params)) {
  1006. return;
  1007. }
  1008. $scope.paramsModel = tableParamsGetter;
  1009. $scope.params = params;
  1010. }), false);
  1011. if ($attrs.showFilter) {
  1012. $scope.$parent.$watch($attrs.showFilter, function(value) {
  1013. $scope.show_filter = value;
  1014. });
  1015. }
  1016. if ($attrs.disableFilter) {
  1017. $scope.$parent.$watch($attrs.disableFilter, function(value) {
  1018. $scope.$filterRow.disabled = value;
  1019. });
  1020. }
  1021. };
  1022. function commonInit(){
  1023. ngTableEventsChannel.onAfterReloadData(bindDataToScope, $scope, isMyPublisher);
  1024. ngTableEventsChannel.onPagesChanged(bindPagesToScope, $scope, isMyPublisher);
  1025. function bindDataToScope(params, newDatapage){
  1026. if (params.settings().groupBy) {
  1027. $scope.$groups = newDatapage;
  1028. } else {
  1029. $scope.$data = newDatapage;
  1030. }
  1031. }
  1032. function bindPagesToScope(params, newPages){
  1033. $scope.pages = newPages
  1034. }
  1035. function isMyPublisher(publisher){
  1036. return $scope.params === publisher;
  1037. }
  1038. }
  1039. commonInit();
  1040. }]);
  1041. /**
  1042. * @ngdoc service
  1043. * @name ngTableColumn
  1044. * @module ngTable
  1045. * @description
  1046. * Service to construct a $column definition used by {@link ngTable ngTable} directive
  1047. */
  1048. app.factory('ngTableColumn', [function () {
  1049. var defaults = {
  1050. 'class': function(){ return ''; },
  1051. filter: function(){ return false; },
  1052. filterData: angular.noop,
  1053. headerTemplateURL: function(){ return false; },
  1054. headerTitle: function(){ return ''; },
  1055. sortable: function(){ return false; },
  1056. show: function(){ return true; },
  1057. title: function(){ return ''; },
  1058. titleAlt: function(){ return ''; }
  1059. };
  1060. /**
  1061. * @ngdoc method
  1062. * @name ngTableColumn#buildColumn
  1063. * @description Creates a $column for use within a header template
  1064. *
  1065. * @param {Object} column an existing $column or simple column data object
  1066. * @param {Scope} defaultScope the $scope to supply to the $column getter methods when not supplied by caller
  1067. * @returns {Object} a $column object
  1068. */
  1069. function buildColumn(column, defaultScope){
  1070. // note: we're not modifying the original column object. This helps to avoid unintended side affects
  1071. var extendedCol = Object.create(column);
  1072. for (var prop in defaults) {
  1073. if (extendedCol[prop] === undefined) {
  1074. extendedCol[prop] = defaults[prop];
  1075. }
  1076. if(!angular.isFunction(extendedCol[prop])){
  1077. // wrap raw field values with "getter" functions
  1078. // - this is to ensure consistency with how ngTable.compile builds columns
  1079. // - note that the original column object is being "proxied"; this is important
  1080. // as it ensure that any changes to the original object will be returned by the "getter"
  1081. (function(prop1){
  1082. extendedCol[prop1] = function(){
  1083. return column[prop1];
  1084. };
  1085. })(prop);
  1086. }
  1087. (function(prop1){
  1088. // satisfy the arguments expected by the function returned by parsedAttribute in the ngTable directive
  1089. var getterFn = extendedCol[prop1];
  1090. extendedCol[prop1] = function(){
  1091. if (arguments.length === 0){
  1092. return getterFn.call(column, defaultScope);
  1093. } else {
  1094. return getterFn.apply(column, arguments);
  1095. }
  1096. };
  1097. })(prop);
  1098. }
  1099. return extendedCol;
  1100. }
  1101. return {
  1102. buildColumn: buildColumn
  1103. };
  1104. }]);
  1105. /**
  1106. * ngTable: Table + Angular JS
  1107. *
  1108. * @author Vitalii Savchuk <esvit666@gmail.com>
  1109. * @url https://github.com/esvit/ng-table/
  1110. * @license New BSD License <http://creativecommons.org/licenses/BSD/>
  1111. */
  1112. /**
  1113. * @ngdoc directive
  1114. * @name ngTable
  1115. * @module ngTable
  1116. * @restrict A
  1117. *
  1118. * @description
  1119. * Directive that instantiates {@link ngTableController ngTableController}.
  1120. */
  1121. app.directive('ngTable', ['$q', '$parse',
  1122. function($q, $parse) {
  1123. 'use strict';
  1124. return {
  1125. restrict: 'A',
  1126. priority: 1001,
  1127. scope: true,
  1128. controller: 'ngTableController',
  1129. compile: function(element) {
  1130. var columns = [],
  1131. i = 0,
  1132. row = null;
  1133. // IE 8 fix :not(.ng-table-group) selector
  1134. angular.forEach(angular.element(element.find('tr')), function(tr) {
  1135. tr = angular.element(tr);
  1136. if (!tr.hasClass('ng-table-group') && !row) {
  1137. row = tr;
  1138. }
  1139. });
  1140. if (!row) {
  1141. return;
  1142. }
  1143. angular.forEach(row.find('td'), function(item) {
  1144. var el = angular.element(item);
  1145. if (el.attr('ignore-cell') && 'true' === el.attr('ignore-cell')) {
  1146. return;
  1147. }
  1148. var getAttrValue = function(attr){
  1149. return el.attr('x-data-' + attr) || el.attr('data-' + attr) || el.attr(attr);
  1150. };
  1151. var parsedAttribute = function(attr) {
  1152. var expr = getAttrValue(attr);
  1153. if (!expr){
  1154. return undefined;
  1155. }
  1156. return function(scope, locals) {
  1157. return $parse(expr)(scope, angular.extend(locals || {}, {
  1158. $columns: columns
  1159. }));
  1160. };
  1161. };
  1162. var titleExpr = getAttrValue('title-alt') || getAttrValue('title');
  1163. if (titleExpr){
  1164. el.attr('data-title-text', '{{' + titleExpr + '}}'); // this used in responsive table
  1165. }
  1166. // NOTE TO MAINTAINERS: if you add extra fields to a $column be sure to extend ngTableColumn with
  1167. // a corresponding "safe" default
  1168. columns.push({
  1169. id: i++,
  1170. title: parsedAttribute('title'),
  1171. titleAlt: parsedAttribute('title-alt'),
  1172. headerTitle: parsedAttribute('header-title'),
  1173. sortable: parsedAttribute('sortable'),
  1174. 'class': parsedAttribute('header-class'),
  1175. filter: parsedAttribute('filter'),
  1176. headerTemplateURL: parsedAttribute('header'),
  1177. filterData: parsedAttribute('filter-data'),
  1178. show: (el.attr("ng-if") ? function (scope) {
  1179. return $parse(el.attr("ng-if"))(scope);
  1180. } : undefined)
  1181. });
  1182. });
  1183. return function(scope, element, attrs, controller) {
  1184. scope.$columns = columns = controller.buildColumns(columns);
  1185. controller.setupBindingsToInternalScope(attrs.ngTable);
  1186. controller.loadFilterData(columns);
  1187. controller.compileDirectiveTemplates();
  1188. };
  1189. }
  1190. }
  1191. }
  1192. ]);
  1193. /**
  1194. * @ngdoc directive
  1195. * @name ngTableDynamic
  1196. * @module ngTable
  1197. * @restrict A
  1198. *
  1199. * @description
  1200. * A dynamic version of the {@link ngTable ngTable} directive that accepts a dynamic list of columns
  1201. * definitions to render
  1202. */
  1203. app.directive('ngTableDynamic', ['$parse', function ($parse){
  1204. return {
  1205. restrict: 'A',
  1206. priority: 1001,
  1207. scope: true,
  1208. controller: 'ngTableController',
  1209. compile: function(tElement) {
  1210. var row;
  1211. // IE 8 fix :not(.ng-table-group) selector
  1212. angular.forEach(angular.element(tElement.find('tr')), function(tr) {
  1213. tr = angular.element(tr);
  1214. if (!tr.hasClass('ng-table-group') && !row) {
  1215. row = tr;
  1216. }
  1217. });
  1218. if (!row) {
  1219. return;
  1220. }
  1221. angular.forEach(row.find('td'), function(item) {
  1222. var el = angular.element(item);
  1223. var getAttrValue = function(attr){
  1224. return el.attr('x-data-' + attr) || el.attr('data-' + attr) || el.attr(attr);
  1225. };
  1226. // this used in responsive table
  1227. var titleExpr = getAttrValue('title');
  1228. if (!titleExpr){
  1229. el.attr('data-title-text', '{{$columns[$index].titleAlt(this) || $columns[$index].title(this)}}');
  1230. }
  1231. var showExpr = el.attr('ng-if');
  1232. if (!showExpr){
  1233. el.attr('ng-if', '$columns[$index].show(this)');
  1234. }
  1235. });
  1236. return function (scope, element, attrs, controller) {
  1237. var expr = controller.parseNgTableDynamicExpr(attrs.ngTableDynamic);
  1238. controller.setupBindingsToInternalScope(expr.tableParams);
  1239. controller.compileDirectiveTemplates();
  1240. scope.$watchCollection(expr.columns, function (newCols/*, oldCols*/) {
  1241. scope.$columns = controller.buildColumns(newCols);
  1242. controller.loadFilterData(scope.$columns);
  1243. });
  1244. };
  1245. }
  1246. };
  1247. }]);
  1248. (function(){
  1249. 'use strict';
  1250. angular.module('ngTable')
  1251. .directive('ngTableFilterRow', ngTableFilterRow);
  1252. ngTableFilterRow.$inject = [];
  1253. function ngTableFilterRow(){
  1254. var directive = {
  1255. restrict: 'E',
  1256. replace: true,
  1257. templateUrl: 'ng-table/filterRow.html',
  1258. scope: true,
  1259. controller: 'ngTableFilterRowController'
  1260. };
  1261. return directive;
  1262. }
  1263. })();
  1264. (function(){
  1265. 'use strict';
  1266. angular.module('ngTable')
  1267. .directive('ngTableSorterRow', ngTableSorterRow);
  1268. ngTableSorterRow.$inject = [];
  1269. function ngTableSorterRow(){
  1270. var directive = {
  1271. restrict: 'E',
  1272. replace: true,
  1273. templateUrl: 'ng-table/sorterRow.html',
  1274. scope: true,
  1275. controller: 'ngTableSorterRowController'
  1276. };
  1277. return directive;
  1278. }
  1279. })();
  1280. /**
  1281. * ngTable: Table + Angular JS
  1282. *
  1283. * @author Vitalii Savchuk <esvit666@gmail.com>
  1284. * @url https://github.com/esvit/ng-table/
  1285. * @license New BSD License <http://creativecommons.org/licenses/BSD/>
  1286. */
  1287. /**
  1288. * @ngdoc directive
  1289. * @name ngTablePagination
  1290. * @module ngTable
  1291. * @restrict A
  1292. */
  1293. app.directive('ngTablePagination', ['$compile', 'ngTableEventsChannel',
  1294. function($compile, ngTableEventsChannel) {
  1295. 'use strict';
  1296. return {
  1297. restrict: 'A',
  1298. scope: {
  1299. 'params': '=ngTablePagination',
  1300. 'templateUrl': '='
  1301. },
  1302. replace: false,
  1303. link: function(scope, element/*, attrs*/) {
  1304. ngTableEventsChannel.onAfterReloadData(function(pubParams) {
  1305. scope.pages = pubParams.generatePagesArray();
  1306. }, scope, function(pubParams){
  1307. return pubParams === scope.params;
  1308. });
  1309. scope.$watch('templateUrl', function(templateUrl) {
  1310. if (angular.isUndefined(templateUrl)) {
  1311. return;
  1312. }
  1313. var template = angular.element(document.createElement('div'));
  1314. template.attr({
  1315. 'ng-include': 'templateUrl'
  1316. });
  1317. element.append(template);
  1318. $compile(template)(scope);
  1319. });
  1320. }
  1321. };
  1322. }
  1323. ]);
  1324. angular.module('ngTable').run(['$templateCache', function ($templateCache) {
  1325. $templateCache.put('ng-table/filterRow.html', '<tr ng-show="show_filter" class="ng-table-filters"> <th data-title-text="{{$column.titleAlt(this) || $column.title(this)}}" ng-repeat="$column in $columns" ng-if="$column.show(this)" class="filter"> <div ng-repeat="(name, filter) in $column.filter(this)"> <div ng-include="config.getTemplateUrl(filter)"></div> </div> </th> </tr> ');
  1326. $templateCache.put('ng-table/filters/number.html', '<input type="number" name="{{name}}" ng-disabled="$filterRow.disabled" ng-model="params.filter()[name]" class="input-filter form-control"/> ');
  1327. $templateCache.put('ng-table/filters/select-multiple.html', '<select ng-options="data.id as data.title for data in $column.data" ng-disabled="$filterRow.disabled" multiple ng-multiple="true" ng-model="params.filter()[name]" class="filter filter-select-multiple form-control" name="{{name}}"> </select> ');
  1328. $templateCache.put('ng-table/filters/select.html', '<select ng-options="data.id as data.title for data in $column.data" ng-disabled="$filterRow.disabled" ng-model="params.filter()[name]" class="filter filter-select form-control" name="{{name}}"> <option style="display:none" value=""></option> </select> ');
  1329. $templateCache.put('ng-table/filters/text.html', '<input type="text" name="{{name}}" ng-disabled="$filterRow.disabled" ng-model="params.filter()[name]" class="input-filter form-control"/> ');
  1330. $templateCache.put('ng-table/header.html', '<ng-table-sorter-row></ng-table-sorter-row> <ng-table-filter-row></ng-table-filter-row> ');
  1331. $templateCache.put('ng-table/pager.html', '<div class="ng-cloak ng-table-pager" ng-if="params.data.length"> <div ng-if="params.settings().counts.length" class="ng-table-counts btn-group pull-right"> <button ng-repeat="count in params.settings().counts" type="button" ng-class="{\'active\':params.count()==count}" ng-click="params.count(count)" class="btn btn-default"> <span ng-bind="count"></span> </button> </div> <ul class="pagination ng-table-pagination"> <li ng-class="{\'disabled\': !page.active && !page.current, \'active\': page.current}" ng-repeat="page in pages" ng-switch="page.type"> <a ng-switch-when="prev" ng-click="params.page(page.number)" href="">&laquo;</a> <a ng-switch-when="first" ng-click="params.page(page.number)" href=""><span ng-bind="page.number"></span></a> <a ng-switch-when="page" ng-click="params.page(page.number)" href=""><span ng-bind="page.number"></span></a> <a ng-switch-when="more" ng-click="params.page(page.number)" href="">&#8230;</a> <a ng-switch-when="last" ng-click="params.page(page.number)" href=""><span ng-bind="page.number"></span></a> <a ng-switch-when="next" ng-click="params.page(page.number)" href="">&raquo;</a> </li> </ul> </div> ');
  1332. $templateCache.put('ng-table/sorterRow.html', '<tr> <th title="{{$column.headerTitle(this)}}" ng-repeat="$column in $columns" ng-class="{ \'sortable\': $column.sortable(this), \'sort-asc\': params.sorting()[$column.sortable(this)]==\'asc\', \'sort-desc\': params.sorting()[$column.sortable(this)]==\'desc\' }" ng-click="sortBy($column, $event)" ng-if="$column.show(this)" ng-init="template=$column.headerTemplateURL(this)" class="header {{$column.class(this)}}"> <div ng-if="!template" class="ng-table-header" ng-class="{\'sort-indicator\': params.settings().sortingIndicator==\'div\'}"> <span ng-bind="$column.title(this)" ng-class="{\'sort-indicator\': params.settings().sortingIndicator==\'span\'}"></span> </div> <div ng-if="template" ng-include="template"></div> </th> </tr> ');
  1333. }]);
  1334. return app;
  1335. }));