forked from esvit/ng-table
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ng-table.src.js
633 lines (596 loc) · 26.8 KB
/
ng-table.src.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
(function(angular, factory) {
if (typeof define === 'function' && define.amd) {
define(['angular'], function(angular) {
return factory(angular);
});
} else {
return factory(angular);
}
}(angular || null, function(angular) {
/**
* ngTable: Table + Angular JS
*
* @author Vitalii Savchuk <[email protected]>
* @url https://github.com/esvit/ng-table/
* @license New BSD License <http://creativecommons.org/licenses/BSD/>
*/
/**
* @ngdoc module
* @name ngTable
* @description ngTable: Table + Angular JS
* @example
<doc:example>
<doc:source>
<script>
var app = angular.module('myApp', ['ngTable']);
app.controller('MyCtrl', function($scope) {
$scope.users = [
{name: "Moroni", age: 50},
{name: "Tiancum", age: 43},
{name: "Jacob", age: 27},
{name: "Nephi", age: 29},
{name: "Enos", age: 34}
];
});
</script>
<table ng-table class="table">
<tr ng-repeat="user in users">
<td data-title="'Name'">{{user.name}}</td>
<td data-title="'Age'">{{user.age}}</td>
</tr>
</table>
</doc:source>
</doc:example>
*/
var app = angular.module('ngTable', []);
/**
* ngTable: Table + Angular JS
*
* @author Vitalii Savchuk <[email protected]>
* @url https://github.com/esvit/ng-table/
* @license New BSD License <http://creativecommons.org/licenses/BSD/>
*/
/**
* @ngdoc service
* @name ngTable.factory:ngTableParams
* @description Parameters manager for ngTable
*/
app.factory('ngTableParams', ['$q', '$log', function ($q, $log) {
var isNumber = function (n) {
return !isNaN(parseFloat(n)) && isFinite(n);
};
var ngTableParams = function (baseParameters, baseSettings) {
var self = this;
this.data = [];
/**
* @ngdoc method
* @name ngTable.factory:ngTableParams#parameters
* @methodOf ngTable.factory:ngTableParams
* @description Set new parameters or get current parameters
*
* @param {string} newParameters New parameters
* @param {string} parseParamsFromUrl Flag if parse parameters like in url
* @returns {Object} Current parameters or `this`
*/
this.parameters = function (newParameters, parseParamsFromUrl) {
parseParamsFromUrl = parseParamsFromUrl || false;
if (angular.isDefined(newParameters)) {
for (var key in newParameters) {
var value = newParameters[key];
if (parseParamsFromUrl && key.indexOf('[') >= 0) {
var keys = key.split(/\[(.*)\]/).reverse()
var lastKey = '';
for (var i = 0, len = keys.length; i < len; i++) {
var name = keys[i];
if (name !== '') {
var v = value;
value = {};
value[lastKey = name] = (isNumber(v) ? parseFloat(v) : v);
}
}
if (lastKey === 'sorting') {
params[lastKey] = {};
}
params[lastKey] = angular.extend(params[lastKey] || {}, value[lastKey]);
} else {
params[key] = (isNumber(newParameters[key]) ? parseFloat(newParameters[key]) : newParameters[key]);
}
}
$log.debug && $log.debug('ngTable: set parameters', params);
return this;
}
return params;
};
/**
* @ngdoc method
* @name ngTable.factory:ngTableParams#settings
* @methodOf ngTable.factory:ngTableParams
* @description Set new settings for table
*
* @param {string} newSettings New settings or undefined
* @returns {Object} Current settings or `this`
*/
this.settings = function (newSettings) {
if (angular.isDefined(newSettings)) {
if (angular.isArray(newSettings.data)) {
//auto-set the total from passed in data
newSettings.total = newSettings.data.length;
}
settings = angular.extend(settings, newSettings);
$log.debug && $log.debug('ngTable: set settings', settings);
return this;
}
return settings;
};
/**
* @ngdoc method
* @name ngTable.factory:ngTableParams#page
* @methodOf ngTable.factory:ngTableParams
* @description If parameter page not set return current page else set current page
*
* @param {string} page Page number
* @returns {Object|Number} Current page or `this`
*/
this.page = function (page) {
return angular.isDefined(page) ? this.parameters({'page': page}) : params.page;
};
/**
* @ngdoc method
* @name ngTable.factory:ngTableParams#total
* @methodOf ngTable.factory:ngTableParams
* @description If parameter total not set return current quantity else set quantity
*
* @param {string} total Total quantity of items
* @returns {Object|Number} Current page or `this`
*/
this.total = function (total) {
return angular.isDefined(total) ? this.settings({'total': total}) : settings.total;
};
/**
* @ngdoc method
* @name ngTable.factory:ngTableParams#count
* @methodOf ngTable.factory:ngTableParams
* @description If parameter count not set return current count per page else set count per page
*
* @param {string} count Count per number
* @returns {Object|Number} Count per page or `this`
*/
this.count = function (count) {
// reset to first page because can be blank page
return angular.isDefined(count) ? this.parameters({'count': count, 'page': 1}) : params.count;
};
/**
* @ngdoc method
* @name ngTable.factory:ngTableParams#filter
* @methodOf ngTable.factory:ngTableParams
* @description If parameter page not set return current filter else set current filter
*
* @param {string} filter New filter
* @returns {Object} Current filter or `this`
*/
this.filter = function (filter) {
return angular.isDefined(filter) ? this.parameters({'filter': filter}) : params.filter;
};
/**
* @ngdoc method
* @name ngTable.factory:ngTableParams#sorting
* @methodOf ngTable.factory:ngTableParams
* @description If 'sorting' parameter is not set, return current sorting. Otherwise set current sorting.
*
* @param {string} sorting New sorting
* @returns {Object} Current sorting or `this`
*/
this.sorting = function (sorting) {
if (arguments.length == 2){
var sortArray = {};
sortArray[sorting] = arguments[1];
this.parameters({'sorting': sortArray});
return this;
}
return angular.isDefined(sorting) ? this.parameters({'sorting': sorting}) : params.sorting;
};
/**
* @ngdoc method
* @name ngTable.factory:ngTableParams#isSortBy
* @methodOf ngTable.factory:ngTableParams
* @description Checks sort field
*
* @param {string} field Field name
* @param {string} direction Direction of sorting 'asc' or 'desc'
* @returns {Array} Return true if field sorted by direction
*/
this.isSortBy = function (field, direction) {
return angular.isDefined(params.sorting[field]) && params.sorting[field] == direction;
};
/**
* @ngdoc method
* @name ngTable.factory:ngTableParams#orderBy
* @methodOf ngTable.factory:ngTableParams
* @description Return object of sorting parameters for angular filter
*
* @returns {Array} Array like: [ '-name', '+age' ]
*/
this.orderBy = function () {
var sorting = [];
for (var column in params.sorting) {
sorting.push((params.sorting[column] === "asc" ? "+" : "-") + column);
}
return sorting;
};
/**
* @ngdoc method
* @name ngTable.factory:ngTableParams#getData
* @methodOf ngTable.factory:ngTableParams
* @description Called when updated some of parameters for get new data
*
* @param {Object} $defer promise object
* @param {Object} params New parameters
*/
this.getData = function ($defer, params) {
if (angular.isArray(this.data) && angular.isObject(params)) {
$defer.resolve(this.data.slice((params.page() - 1) * params.count(), params.page() * params.count()));
} else {
$defer.resolve([]);
}
};
/**
* @ngdoc method
* @name ngTable.factory:ngTableParams#getGroups
* @methodOf ngTable.factory:ngTableParams
* @description Return groups for table grouping
*/
this.getGroups = function ($defer, column) {
var defer = $q.defer();
defer.promise.then(function(data) {
var groups = {};
for (var k in data) {
var item = data[k],
groupName = angular.isFunction(column) ? column(item) : item[column];
groups[groupName] = groups[groupName] || {
data: []
};
groups[groupName]['value'] = groupName;
groups[groupName].data.push(item);
}
var result = [];
for (var i in groups) {
result.push(groups[i]);
}
$log.debug && $log.debug('ngTable: refresh groups', result);
$defer.resolve(result);
});
this.getData(defer, self);
};
/**
* @ngdoc method
* @name ngTable.factory:ngTableParams#generatePagesArray
* @methodOf ngTable.factory:ngTableParams
* @description Generate array of pages
*
* @param {boolean} currentPage which page must be active
* @param {boolean} totalItems Total quantity of items
* @param {boolean} pageSize Quantity of items on page
* @returns {Array} Array of pages
*/
this.generatePagesArray = function (currentPage, totalItems, pageSize) {
var maxBlocks, maxPage, maxPivotPages, minPage, numPages, pages;
maxBlocks = 11;
pages = [];
numPages = Math.ceil(totalItems / pageSize);
if (numPages > 1) {
pages.push({
type: 'prev',
number: Math.max(1, currentPage - 1),
active: currentPage > 1
});
pages.push({
type: 'first',
number: 1,
active: currentPage > 1
});
maxPivotPages = Math.round((maxBlocks - 5) / 2);
minPage = Math.max(2, currentPage - maxPivotPages);
maxPage = Math.min(numPages - 1, currentPage + maxPivotPages * 2 - (currentPage - minPage));
minPage = Math.max(2, minPage - (maxPivotPages * 2 - (maxPage - minPage)));
var i = minPage;
while (i <= maxPage) {
if ((i === minPage && i !== 2) || (i === maxPage && i !== numPages - 1)) {
pages.push({
type: 'more',
active: false
});
} else {
pages.push({
type: 'page',
number: i,
active: currentPage !== i
});
}
i++;
}
pages.push({
type: 'last',
number: numPages,
active: currentPage !== numPages
});
pages.push({
type: 'next',
number: Math.min(numPages, currentPage + 1),
active: currentPage < numPages
});
}
return pages;
};
/**
* @ngdoc method
* @name ngTable.factory:ngTableParams#url
* @methodOf ngTable.factory:ngTableParams
* @description Return groups for table grouping
*
* @param {boolean} asString flag indicates return array of string or object
* @returns {Array} If asString = true will be return array of url string parameters else key-value object
*/
this.url = function (asString) {
asString = asString || false;
var pairs = (asString ? [] : {});
for (key in params) {
if (params.hasOwnProperty(key)) {
var item = params[key],
name = encodeURIComponent(key);
if (typeof item === "object") {
for (var subkey in item) {
if (!angular.isUndefined(item[subkey]) && item[subkey] !== "") {
var pname = name + "[" + encodeURIComponent(subkey) + "]";
if (asString) {
pairs.push(pname + "=" + item[subkey]);
} else {
pairs[pname] = item[subkey];
}
}
}
} else if (!angular.isFunction(item) && !angular.isUndefined(item) && item !== "") {
if (asString) {
pairs.push(name + "=" + encodeURIComponent(item));
} else {
pairs[name] = encodeURIComponent(item);
}
}
}
}
return pairs;
};
/**
* @ngdoc method
* @name ngTable.factory:ngTableParams#reload
* @methodOf ngTable.factory:ngTableParams
* @description Reload table data
*/
this.reload = function() {
var $defer = $q.defer(),
self = this;
settings.$loading = true;
if (settings.groupBy) {
settings.getGroups($defer, settings.groupBy, this);
} else {
settings.getData($defer, this);
}
$log.debug && $log.debug('ngTable: reload data');
$defer.promise.then(function(data) {
settings.$loading = false;
$log.debug && $log.debug('ngTable: current scope', settings.$scope);
if (settings.groupBy) {
self.data = settings.$scope.$groups = data;
} else {
self.data = settings.$scope.$data = data;
}
settings.$scope.pages = self.generatePagesArray(self.page(), self.total(), self.count());
});
};
this.reloadPages = function () {
var self = this;
settings.$scope.pages = self.generatePagesArray(self.page(), self.total(), self.count());
};
var params = this.$params = {
page: 1,
count: 1,
filter: {},
sorting: {},
group: {},
groupBy: null
};
var settings = {
$scope: null, // set by ngTable controller
$loading: false,
data: null, //allows data to be set when table is initialized
total: 0,
counts: [10, 25, 50, 100],
getGroups: this.getGroups,
getData: this.getData
};
this.settings(baseSettings);
this.parameters(baseParameters, true);
return this;
};
return ngTableParams;
}]);
/**
* ngTable: Table + Angular JS
*
* @author Vitalii Savchuk <[email protected]>
* @url https://github.com/esvit/ng-table/
* @license New BSD License <http://creativecommons.org/licenses/BSD/>
*/
/**
* @ngdoc object
* @name ngTable.directive:ngTable.ngTableController
*
* @description
* Each {@link ngTable.directive:ngTable ngTable} directive creates an instance of `ngTableController`
*/
var ngTableController = ['$scope', 'ngTableParams', '$q', function($scope, ngTableParams, $q) {
$scope.$loading = false;
if (!$scope.params) {
$scope.params = new ngTableParams();
}
$scope.params.settings().$scope = $scope;
$scope.$watch('params.$params', function(params) {
$scope.params.settings().$scope = $scope;
$scope.params.reload();
}, true);
$scope.sortBy = function (column, event) {
var parsedSortable = $scope.parse(column.sortable);
if (!parsedSortable) {
return;
}
var sorting = $scope.params.sorting() && $scope.params.sorting()[parsedSortable] && ($scope.params.sorting()[parsedSortable] === "desc");
var sortingParams = event.ctrlKey ? $scope.params.sorting() : {};
sortingParams[parsedSortable] = (sorting ? 'asc' : 'desc');
$scope.params.parameters({
sorting: sortingParams
});
};
}];
/**
* ngTable: Table + Angular JS
*
* @author Vitalii Savchuk <[email protected]>
* @url https://github.com/esvit/ng-table/
* @license New BSD License <http://creativecommons.org/licenses/BSD/>
*/
/**
* @ngdoc directive
* @name ngTable.directive:ngTable
* @restrict A
*
* @description
* Directive that instantiates {@link ngTable.directive:ngTable.ngTableController ngTableController}.
*/
app.directive('ngTable', ['$compile', '$q', '$parse',
function ($compile, $q, $parse) {
'use strict';
return {
restrict: 'A',
priority: 1001,
scope: true,
controller: ngTableController,
compile: function (element) {
var columns = [], i = 0, row = null;
// custom header
var thead = element.find('thead');
// IE 8 fix :not(.ng-table-group) selector
angular.forEach(angular.element(element.find('tr')), function(tr) {
tr = angular.element(tr);
if (!tr.hasClass('ng-table-group') && !row) {
row = tr;
}
});
if (!row) {
return;
}
angular.forEach(row.find('td'), function (item) {
var el = angular.element(item);
if (el.attr('ignore-cell') && 'true' === el.attr('ignore-cell')) {
return;
}
var parsedAttribute = function(attr, defaultValue) {
return function(scope) {
return $parse(el.attr('x-data-' + attr) || el.attr('data-' + attr) || el.attr(attr))(scope, {
$columns: columns
}) || defaultValue;
};
};
var parsedTitle = parsedAttribute('title', ' '),
headerTemplateURL = parsedAttribute('header', false),
filter = parsedAttribute('filter', false)(),
filterTemplateURL = false;
if (filter && filter.templateURL) {
filterTemplateURL = filter.templateURL;
delete filter.templateURL;
}
el.attr('data-title-text', parsedTitle()); // this used in responsive table
columns.push({
id: i++,
title: parsedTitle,
sortable: parsedAttribute('sortable', false),
'class': el.attr('x-data-header-class') || el.attr('data-header-class') || el.attr("header-class"),
filter: filter,
filterTemplateURL: filterTemplateURL,
headerTemplateURL: headerTemplateURL,
filterData: (el.attr("filter-data") ? el.attr("filter-data") : null),
show: (el.attr("ng-show") ? function (scope) {
return $parse(el.attr("ng-show"))(scope);
} : function () {
return true;
})
});
});
return function (scope, element, attrs) {
scope.$loading = false;
scope.$columns = columns;
scope.$watch(attrs.ngTable, (function (params) {
if (angular.isUndefined(params)) {
return;
}
scope.paramsModel = $parse(attrs.ngTable);
scope.params = params;
}), true);
scope.parse = function (text) {
return angular.isDefined(text) ? text(scope) : '';
};
if (attrs.showFilter) {
scope.$parent.$watch(attrs.showFilter, function (value) {
scope.show_filter = value;
});
}
angular.forEach(columns, function (column) {
var def;
if (!column.filterData) {
return;
}
def = $parse(column.filterData)(scope, {
$column: column
});
if (!(angular.isObject(def) && angular.isObject(def.promise))) {
throw new Error('Function ' + column.filterData + ' must be instance of $q.defer()');
}
delete column['filterData'];
return def.promise.then(function (data) {
if (!angular.isArray(data)) {
data = [];
}
data.unshift({
title: '-',
id: ''
});
column.data = data;
});
});
if (!element.hasClass('ng-table')) {
scope.templates = {
header: (attrs.templateHeader ? attrs.templateHeader : 'ng-table/header.html'),
pagination: (attrs.templatePagination ? attrs.templatePagination : 'ng-table/pager.html')
};
var headerTemplate = thead.length > 0 ? thead : angular.element(document.createElement('thead')).attr('ng-include', 'templates.header');
var paginationTemplate = angular.element(document.createElement('div')).attr('ng-include', 'templates.pagination');
element.find('thead').remove();
var tbody = element.find('tbody');
element.prepend(headerTemplate);
$compile(headerTemplate)(scope);
$compile(paginationTemplate)(scope);
element.addClass('ng-table');
return element.after(paginationTemplate);
}
};
}
}
}
]);
angular.module('ngTable').run(['$templateCache', function ($templateCache) {
$templateCache.put('ng-table/filters/select-multiple.html', '<select ng-options="data.id as data.title for data in column.data" multiple ng-multiple="true" ng-model="params.filter()[name]" ng-show="filter==\'select-multiple\'" class="filter filter-select-multiple form-control"> </select>');
$templateCache.put('ng-table/filters/select.html', '<select ng-options="data.id as data.title for data in column.data" ng-model="params.filter()[name]" ng-show="filter==\'select\'" class="filter filter-select form-control"> </select>');
$templateCache.put('ng-table/filters/text.html', '<input type="text" ng-model="params.filter()[name]" ng-if="filter==\'text\'" class="input-filter form-control"/>');
$templateCache.put('ng-table/header.html', '<tr> <th ng-repeat="column in $columns" ng-class="{ \'sortable\': parse(column.sortable), \'sort-asc\': params.sorting()[parse(column.sortable)]==\'asc\', \'sort-desc\': params.sorting()[parse(column.sortable)]==\'desc\' }" ng-click="sortBy(column, $event)" ng-show="column.show(this)" ng-init="template=column.headerTemplateURL(this)" class="header {{column.class}}"> <div ng-if="!template" ng-show="!template" ng-bind="parse(column.title)"></div> <div ng-if="template" ng-show="template"><div ng-include="template"></div></div> </th> </tr> <tr ng-show="show_filter" class="ng-table-filters"> <th ng-repeat="column in $columns" ng-show="column.show(this)" class="filter"> <div ng-repeat="(name, filter) in column.filter"> <div ng-if="column.filterTemplateURL" ng-show="column.filterTemplateURL"> <div ng-include="column.filterTemplateURL"></div> </div> <div ng-if="!column.filterTemplateURL" ng-show="!column.filterTemplateURL"> <div ng-include="\'ng-table/filters/\' + filter + \'.html\'"></div> </div> </div> </th> </tr>');
$templateCache.put('ng-table/pager.html', '<div class="ng-cloak ng-table-pager"> <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}" ng-repeat="page in pages" ng-switch="page.type"> <a ng-switch-when="prev" ng-click="params.page(page.number)" href="">«</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="">…</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="">»</a> </li> </ul> </div> ');
}]);
return app;
}));