1 ng.module('smart-table')
2 .directive('stSort', ['stConfig', '$parse', '$timeout', function (stConfig, $parse, $timeout) {
6 link: function (scope, element, attr, ctrl) {
8 var predicate = attr.stSort;
9 var getter = $parse(predicate);
11 var classAscent = attr.stClassAscent || stConfig.sort.ascentClass;
12 var classDescent = attr.stClassDescent || stConfig.sort.descentClass;
13 var stateClasses = [classAscent, classDescent];
15 var skipNatural = attr.stSkipNatural !== undefined ? attr.stSkipNatural : stConfig.sort.skipNatural;
16 var descendingFirst = attr.stDescendingFirst !== undefined ? attr.stDescendingFirst : stConfig.sort.descendingFirst;
18 var throttle = attr.stDelay || stConfig.sort.delay;
20 if (attr.stSortDefault) {
21 sortDefault = scope.$eval(attr.stSortDefault) !== undefined ? scope.$eval(attr.stSortDefault) : attr.stSortDefault;
24 //view --> table state
26 if (descendingFirst) {
27 index = index === 0 ? 2 : index - 1;
33 predicate = ng.isFunction(getter(scope)) || ng.isArray(getter(scope)) ? getter(scope) : attr.stSort;
34 if (index % 3 === 0 && !!skipNatural !== true) {
37 ctrl.tableState().sort = {};
38 ctrl.tableState().pagination.start = 0;
39 func = ctrl.pipe.bind(ctrl);
41 func = ctrl.sortBy.bind(ctrl, predicate, index % 2 === 0);
43 if (promise !== null) {
44 $timeout.cancel(promise);
49 promise = $timeout(func, throttle);
53 element.bind('click', function sortClick () {
60 index = sortDefault === 'reverse' ? 1 : 0;
64 //table state --> view
65 scope.$watch(function () {
66 return ctrl.tableState().sort;
67 }, function (newValue) {
68 if (newValue.predicate !== predicate) {
71 .removeClass(classAscent)
72 .removeClass(classDescent);
74 index = newValue.reverse === true ? 2 : 1;
76 .removeClass(stateClasses[index % 2])
77 .addClass(stateClasses[index - 1]);