Skip to content

Instantly share code, notes, and snippets.

@apolishch
Last active August 29, 2015 14:00
Show Gist options
  • Save apolishch/11151489 to your computer and use it in GitHub Desktop.
Save apolishch/11151489 to your computer and use it in GitHub Desktop.
app.directive('sortable', [->
sortClasses =
'-1': 'sort-up'
'1': 'sort-down'
restrict: 'A'
scope: {
biDirectional: '@'
initialDirection: '@'
sortEventType: '@'
sortEvent: '@'
sortableKey: '&'
sortCallback: '&'
sortableCollection: '='
}
link: (scope, element, attrs)->
element.addClass('sortable')
scope.sortableKey = scope.sortableKey()
scope.biDirectional = JSON.parse(scope.biDirectional)
if(scope.initialDirection == 'ascending')
scope.direction = -1
else
scope.direction = 1
scope.sortEventType = 'element' unless scope.sortEventType == 'scope'
scope.sortEvent = 'click' unless scope.sortEvent
sortFunction = ->
scope.sortableCollection.sort (a,b) ->
if a[scope.sortableKey] < b[scope.sortableKey]
-1*scope.direction
else if a[scope.sortableKey] is b[scope.sortableKey]
0
else
1*scope.direction
if scope.biDirectional
element.addClass(sortClasses[scope.direction.toString()])
element.removeClass(sortClasses[(-1*scope.direction).toString()])
scope.direction = scope.direction*-1
scope.sortCallback()
scope.$apply()
if scope.sortEventType == 'element'
element.on(scope.sortEvent, sortFunction)
else if scope.sortEventType == 'scope'
scope.$on(scope.sortEvent, sortFunction)
])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment