JSFiddle - React, Tailwind, and code Playground
by Blake Dietz
HTML
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.16/angular.min.js"></script>
<table ng-controller="ATableController">
<thead>
<tr>
<th>Column1</th>
<th>Column2</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="row in tableData" >
<td>{{row.col1}}</td>
<td>{{row.col2}}</td>
</tr>
</tbody>
</table>
JavaScript
(function ()
{
angular.module('app', [])
.controller('ATableController',
['$scope',
function($scope)
{
$scope.tableData= [{'col1' : 'foo','col2' : 'bar'},
{'col1' : 'foo','col2' : 'bar'},
{'col1' : 'foo','col2' : 'bar'},
{'col1' : 'foo','col2' : 'bar'}];
}])
.directive('tableSort', [function()
{
return {
restrict : 'A',
replace : false,
scope :
{
tableSortData : '=',
tableSortRowAccessor : '=',
tableSortPrimer : '='
},
link : function(scope, element)
{
var sortInfo =
{
currentSortField : '',
'ascSort' : true
};
// Await click events on header
element.find('th').on('click.header', function(event)
{
var field = $(event.target).attr('field-name');
field ? sort(field) : '';
});
function sortBy(field, reverse, primer, rowAccessor)
{
var key;
key = primer ?
function(x) { return primer(x[field]) }
:
function(x) { return x[field] };
reverse = [-1, 1][+!!reverse];
return function (a, b)
{
if (rowAccessor)
{
var asc = (reverse == -1) ? true : false;
a = rowAccessor(a, asc, key);
b = rowAccessor(b, asc, key);
}
else
{
a = key(a);
b = key(b);
}
return reverse * ((a > b) - (b > a));
}
}
function sort(rowField)
{
if (sortInfo.currentSortField == rowField)
{
sortInfo.ascSort = !sortInfo.ascSort;
}
else
{
...