5 (function (ng, undefined){
8 ng.module('smart-table', []).run(['$templateCache', function ($templateCache) {
9 $templateCache.put('template/smart-table/pagination.html',
10 '<nav ng-if="numPages && pages.length >= 2"><ul class="pagination">' +
11 '<li ng-repeat="page in pages" ng-class="{active: page==currentPage}"><a href="javascript: void(0);" ng-click="selectPage(page)">{{page}}</a></li>' +
16 ng.module('smart-table')
17 .constant('stConfig', {
19 template: 'template/smart-table/pagination.html',
29 selectedClass: 'st-selected'
32 ascentClass: 'st-sort-ascent',
33 descentClass: 'st-sort-descent',
34 descendingFirst: false,
42 ng.module('smart-table')
43 .controller('stTableController', ['$scope', '$parse', '$filter', '$attrs', function StTableController ($scope, $parse, $filter, $attrs) {
44 var propertyName = $attrs.stTable;
45 var displayGetter = $parse(propertyName);
46 var displaySetter = displayGetter.assign;
48 var orderBy = $filter('orderBy');
49 var filter = $filter('filter');
50 var safeCopy = copyRefs(displayGetter($scope));
60 var pipeAfterSafeCopy = true;
64 function copyRefs (src) {
65 return src ? [].concat(src) : [];
68 function updateSafeCopy () {
69 safeCopy = copyRefs(safeGetter($scope));
70 if (pipeAfterSafeCopy === true) {
75 function deepDelete (object, path) {
76 if (path.indexOf('.') != -1) {
77 var partials = path.split('.');
78 var key = partials.pop();
79 var parentPath = partials.join('.');
80 var parentObject = $parse(parentPath)(object)
81 delete parentObject[key];
82 if (Object.keys(parentObject).length == 0) {
83 deepDelete(object, parentPath);
90 if ($attrs.stSafeSrc) {
91 safeGetter = $parse($attrs.stSafeSrc);
92 $scope.$watch(function () {
93 var safeSrc = safeGetter($scope);
94 return safeSrc && safeSrc.length ? safeSrc[0] : undefined;
95 }, function (newValue, oldValue) {
96 if (newValue !== oldValue) {
100 $scope.$watch(function () {
101 var safeSrc = safeGetter($scope);
102 return safeSrc ? safeSrc.length : 0;
103 }, function (newValue, oldValue) {
104 if (newValue !== safeCopy.length) {
108 $scope.$watch(function () {
109 return safeGetter($scope);
110 }, function (newValue, oldValue) {
111 if (newValue !== oldValue) {
112 tableState.pagination.start = 0;
120 * @param {Function | String} predicate - function or string which will be used as predicate for the sorting
121 * @param [reverse] - if you want to reverse the order
123 this.sortBy = function sortBy (predicate, reverse) {
124 tableState.sort.predicate = predicate;
125 tableState.sort.reverse = reverse === true;
127 if (ng.isFunction(predicate)) {
128 tableState.sort.functionName = predicate.name;
130 delete tableState.sort.functionName;
133 tableState.pagination.start = 0;
138 * search matching rows
139 * @param {String} input - the input string
140 * @param {String} [predicate] - the property name against you want to check the match, otherwise it will search on all properties
142 this.search = function search (input, predicate) {
143 var predicateObject = tableState.search.predicateObject || {};
144 var prop = predicate ? predicate : '$';
146 input = ng.isString(input) ? input.trim() : input;
147 $parse(prop).assign(predicateObject, input);
148 // to avoid to filter out null value
150 deepDelete(predicateObject, prop);
152 tableState.search.predicateObject = predicateObject;
153 tableState.pagination.start = 0;
158 * this will chain the operations of sorting and filtering based on the current table state (sort options, filtering, ect)
160 this.pipe = function pipe () {
161 var pagination = tableState.pagination;
163 filtered = tableState.search.predicateObject ? filter(safeCopy, tableState.search.predicateObject) : safeCopy;
164 if (tableState.sort.predicate) {
165 filtered = orderBy(filtered, tableState.sort.predicate, tableState.sort.reverse);
167 pagination.totalItemCount = filtered.length;
168 if (pagination.number !== undefined) {
169 pagination.numberOfPages = filtered.length > 0 ? Math.ceil(filtered.length / pagination.number) : 1;
170 pagination.start = pagination.start >= filtered.length ? (pagination.numberOfPages - 1) * pagination.number : pagination.start;
171 output = filtered.slice(pagination.start, pagination.start + parseInt(pagination.number));
173 displaySetter($scope, output || filtered);
177 * select a dataRow (it will add the attribute isSelected to the row object)
178 * @param {Object} row - the row to select
179 * @param {String} [mode] - "single" or "multiple" (multiple by default)
181 this.select = function select (row, mode) {
182 var rows = copyRefs(displayGetter($scope));
183 var index = rows.indexOf(row);
185 if (mode === 'single') {
186 row.isSelected = row.isSelected !== true;
188 lastSelected.isSelected = false;
190 lastSelected = row.isSelected === true ? row : undefined;
192 rows[index].isSelected = !rows[index].isSelected;
198 * take a slice of the current sorted/filtered collection (pagination)
200 * @param {Number} start - start index of the slice
201 * @param {Number} number - the number of item in the slice
203 this.slice = function splice (start, number) {
204 tableState.pagination.start = start;
205 tableState.pagination.number = number;
210 * return the current state of the table
211 * @returns {{sort: {}, search: {}, pagination: {start: number}}}
213 this.tableState = function getTableState () {
217 this.getFilteredCollection = function getFilteredCollection () {
218 return filtered || safeCopy;
222 * Use a different filter function than the angular FilterFilter
223 * @param filterName the name under which the custom filter is registered
225 this.setFilterFunction = function setFilterFunction (filterName) {
226 filter = $filter(filterName);
230 * Use a different function than the angular orderBy
231 * @param sortFunctionName the name under which the custom order function is registered
233 this.setSortFunction = function setSortFunction (sortFunctionName) {
234 orderBy = $filter(sortFunctionName);
238 * Usually when the safe copy is updated the pipe function is called.
239 * Calling this method will prevent it, which is something required when using a custom pipe function
241 this.preventPipeOnWatch = function preventPipe () {
242 pipeAfterSafeCopy = false;
245 .directive('stTable', function () {
248 controller: 'stTableController',
249 link: function (scope, element, attr, ctrl) {
251 if (attr.stSetFilter) {
252 ctrl.setFilterFunction(attr.stSetFilter);
255 if (attr.stSetSort) {
256 ctrl.setSortFunction(attr.stSetSort);
262 ng.module('smart-table')
263 .directive('stSearch', ['stConfig', '$timeout','$parse', function (stConfig, $timeout, $parse) {
266 link: function (scope, element, attr, ctrl) {
267 var tableCtrl = ctrl;
269 var throttle = attr.stDelay || stConfig.search.delay;
270 var event = attr.stInputEvent || stConfig.search.inputEvent;
272 attr.$observe('stSearch', function (newValue, oldValue) {
273 var input = element[0].value;
274 if (newValue !== oldValue && input) {
275 ctrl.tableState().search = {};
276 tableCtrl.search(input, newValue);
280 //table state -> view
281 scope.$watch(function () {
282 return ctrl.tableState().search;
283 }, function (newValue, oldValue) {
284 var predicateExpression = attr.stSearch || '$';
285 if (newValue.predicateObject && $parse(predicateExpression)(newValue.predicateObject) !== element[0].value) {
286 element[0].value = $parse(predicateExpression)(newValue.predicateObject) || '';
290 // view -> table state
291 element.bind(event, function (evt) {
292 evt = evt.originalEvent || evt;
293 if (promise !== null) {
294 $timeout.cancel(promise);
297 promise = $timeout(function () {
298 tableCtrl.search(evt.target.value, attr.stSearch || '');
306 ng.module('smart-table')
307 .directive('stSelectRow', ['stConfig', function (stConfig) {
314 link: function (scope, element, attr, ctrl) {
315 var mode = attr.stSelectMode || stConfig.select.mode;
316 element.bind('click', function () {
317 scope.$apply(function () {
318 ctrl.select(scope.row, mode);
322 scope.$watch('row.isSelected', function (newValue) {
323 if (newValue === true) {
324 element.addClass(stConfig.select.selectedClass);
326 element.removeClass(stConfig.select.selectedClass);
333 ng.module('smart-table')
334 .directive('stSort', ['stConfig', '$parse', '$timeout', function (stConfig, $parse, $timeout) {
338 link: function (scope, element, attr, ctrl) {
340 var predicate = attr.stSort;
341 var getter = $parse(predicate);
343 var classAscent = attr.stClassAscent || stConfig.sort.ascentClass;
344 var classDescent = attr.stClassDescent || stConfig.sort.descentClass;
345 var stateClasses = [classAscent, classDescent];
347 var skipNatural = attr.stSkipNatural !== undefined ? attr.stSkipNatural : stConfig.sort.skipNatural;
348 var descendingFirst = attr.stDescendingFirst !== undefined ? attr.stDescendingFirst : stConfig.sort.descendingFirst;
350 var throttle = attr.stDelay || stConfig.sort.delay;
352 if (attr.stSortDefault) {
353 sortDefault = scope.$eval(attr.stSortDefault) !== undefined ? scope.$eval(attr.stSortDefault) : attr.stSortDefault;
356 //view --> table state
358 if (descendingFirst) {
359 index = index === 0 ? 2 : index - 1;
365 predicate = ng.isFunction(getter(scope)) || ng.isArray(getter(scope)) ? getter(scope) : attr.stSort;
366 if (index % 3 === 0 && !!skipNatural !== true) {
369 ctrl.tableState().sort = {};
370 ctrl.tableState().pagination.start = 0;
371 func = ctrl.pipe.bind(ctrl);
373 func = ctrl.sortBy.bind(ctrl, predicate, index % 2 === 0);
375 if (promise !== null) {
376 $timeout.cancel(promise);
381 promise = $timeout(func, throttle);
385 element.bind('click', function sortClick () {
392 index = sortDefault === 'reverse' ? 1 : 0;
396 //table state --> view
397 scope.$watch(function () {
398 return ctrl.tableState().sort;
399 }, function (newValue) {
400 if (newValue.predicate !== predicate) {
403 .removeClass(classAscent)
404 .removeClass(classDescent);
406 index = newValue.reverse === true ? 2 : 1;
408 .removeClass(stateClasses[index % 2])
409 .addClass(stateClasses[index - 1]);
416 ng.module('smart-table')
417 .directive('stPagination', ['stConfig', function (stConfig) {
423 stDisplayedPages: '=?',
426 templateUrl: function (element, attrs) {
427 if (attrs.stTemplate) {
428 return attrs.stTemplate;
430 return stConfig.pagination.template;
432 link: function (scope, element, attrs, ctrl) {
434 scope.stItemsByPage = scope.stItemsByPage ? +(scope.stItemsByPage) : stConfig.pagination.itemsByPage;
435 scope.stDisplayedPages = scope.stDisplayedPages ? +(scope.stDisplayedPages) : stConfig.pagination.displayedPages;
437 scope.currentPage = 1;
441 var paginationState = ctrl.tableState().pagination;
445 var prevPage = scope.currentPage;
446 scope.totalItemCount = paginationState.totalItemCount;
447 scope.currentPage = Math.floor(paginationState.start / paginationState.number) + 1;
449 start = Math.max(start, scope.currentPage - Math.abs(Math.floor(scope.stDisplayedPages / 2)));
450 end = start + scope.stDisplayedPages;
452 if (end > paginationState.numberOfPages) {
453 end = paginationState.numberOfPages + 1;
454 start = Math.max(1, end - scope.stDisplayedPages);
458 scope.numPages = paginationState.numberOfPages;
460 for (i = start; i < end; i++) {
464 if (prevPage !== scope.currentPage) {
465 scope.stPageChange({newPage: scope.currentPage});
469 //table state --> view
470 scope.$watch(function () {
471 return ctrl.tableState().pagination;
474 //scope --> table state (--> view)
475 scope.$watch('stItemsByPage', function (newValue, oldValue) {
476 if (newValue !== oldValue) {
481 scope.$watch('stDisplayedPages', redraw);
483 //view -> table state
484 scope.selectPage = function (page) {
485 if (page > 0 && page <= scope.numPages) {
486 ctrl.slice((page - 1) * scope.stItemsByPage, scope.stItemsByPage);
490 if (!ctrl.tableState().pagination.number) {
491 ctrl.slice(0, scope.stItemsByPage);
497 ng.module('smart-table')
498 .directive('stPipe', ['stConfig', '$timeout', function (config, $timeout) {
506 pre: function (scope, element, attrs, ctrl) {
508 var pipePromise = null;
510 if (ng.isFunction(scope.stPipe)) {
511 ctrl.preventPipeOnWatch();
512 ctrl.pipe = function () {
514 if (pipePromise !== null) {
515 $timeout.cancel(pipePromise)
518 pipePromise = $timeout(function () {
519 scope.stPipe(ctrl.tableState(), ctrl);
520 }, config.pipe.delay);
527 post: function (scope, element, attrs, ctrl) {