Created
January 28, 2016 16:46
-
-
Save uhtred/02c6df0219c97909aca1 to your computer and use it in GitHub Desktop.
Angular: Sort Column Directive
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
@Deps font awesome icons, lodash | |
@Usage | |
<table> | |
<thead sort-column="sortPersons"> | |
<tr> | |
<th sort-column-name="name">Name</tr> | |
<th sort-column-name="number">Number</tr> | |
</tr> | |
<thead> | |
<tbody> | |
<tr ng-repeat="person in vm.persons | orderBy: sortPersons"> | |
<td>{{person.name}}</td> | |
<td>{{person.number}}</td> | |
</tr> | |
</tbody> | |
</table> | |
.sort-column { | |
&--inactive { | |
i { | |
color: #B5B5B5; | |
} | |
} | |
} | |
*/ | |
(function() { | |
'use strict'; | |
function sortColumn() { | |
function link(scope, elem, attrs) { | |
var columnName = '', | |
currentElement, | |
currentIcon, | |
cssClass = { | |
up: 'fa-caret-up', | |
down: 'fa-caret-down', | |
inactive: 'sort-column--inactive', | |
asc: 'sort-column--asc', | |
desc: 'sort-column--desc' | |
}; | |
function isDesc() { | |
return _.startsWith(scope.sortColumn, '-'); | |
} | |
function revert() { | |
isDesc() ? makeAsc() : makeDesc(); | |
} | |
function makeAsc() { | |
scope.sortColumn = _.trimLeft(columnName, '-'); | |
currentIcon.addClass(cssClass.down); | |
} | |
function makeDesc() { | |
scope.sortColumn = '-' + _.trimLeft(columnName, '-'); | |
currentIcon.addClass(cssClass.up); | |
} | |
function activeCurrent() { | |
currentElement.removeClass(cssClass.inactive); | |
} | |
function disableAll() { | |
elem.find('[sort-column-name]') | |
.addClass(cssClass.inactive) | |
.find('i') | |
.removeClass(cssClass.up); | |
} | |
function sort() { | |
disableAll(); | |
currentIcon = currentElement.find('i'); | |
columnName = currentElement.attr('sort-column-name'); | |
activeCurrent(); | |
} | |
function setColumnElement() { | |
currentElement = elem.find('[sort-column-name="' + scope.sortColumn + '"]'); | |
} | |
function getFirstColumn() { | |
return elem.find('[sort-column-name]:eq(0)') | |
.attr('sort-column-name'); | |
} | |
function init() { | |
scope.sortColumn = scope.sortColumnInit || getFirstColumn(); | |
setColumnElement(); | |
sort(); | |
} | |
elem.find('[sort-column-name]') | |
.on('click', function(e) { | |
currentElement = angular.element(e.currentTarget); | |
sort(); | |
scope.$apply(function() { | |
revert(); | |
}); | |
activeCurrent(); | |
}); | |
init(); | |
} | |
return { | |
restrict: 'A', | |
link: link, | |
scope: { | |
sortColumn: '=', | |
sortColumnInit: '@' | |
} | |
}; | |
} | |
angular.module('sortColumn', []) | |
.directive('sortColumn', sortColumn); | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment