angular sort

sort header directive

by shengoo

HTML

<div ng-app="myApp"> 
<div ng-controller="Controller">
    <table width="50%">
    <colgroup>
      <col width="40%"/>
      <col width="50%"/>
      <col width="10%"/>
    </colgroup>
    <thead>
        <tr>
            <th sort order="'name'" by="order" reverse="reverse">Name</th>
            <th>Phone</th>
            <th sort order="'age'" by="order" reverse="reverse">Age</th>        
        </tr>
    </thead>
    <tbody>
        <tr ng-repeat="friend in friends | orderBy:order:reverse">
            <td>{{friend.name}}</td>
            <td>{{friend.phone}}</td>
            <td>{{friend.age}}</td>
        </tr>
    </tbody>
</table>
  <br/>
  Order : <b>{{order}}</b> reverse : <b>{{reverse}}</b>
  </div>
</div>

CSS

</style>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css" rel="stylesheet">
<style>

JavaScript

function Controller($scope) {
  $scope.order = 'name';
  $scope.reverse = false;
    

  $scope.friends = [
    {name:'John', phone:'555-1212', age:10},
    {name:'Mary', phone:'555-9876', age:19},
    {name:'Mike', phone:'555-4321', age:21},
    {name:'Adam', phone:'555-5678', age:35},
    {name:'Julie', phone:'555-8765', age:29}]; 
}

angular.module('myApp', []).directive("sort", function() {
return {
    restrict: 'A',
    transclude: true,
    template : 
      '<a ng-click="onClick()">'+
        '<span ng-transclude></span>'+ 
        '<i class="glyphicon" ng-class="{\'glyphicon-sort-by-alphabet\' : order === by && !reverse,  \'glyphicon-sort-by-alphabet-alt\' : order===by && reverse}"></i>'+
      '</a>',
    scope: {
      order: '=',
      by: '=',
      reverse : '='
    },
    link: function(scope, element, attrs) {
      scope.onClick = function () {
        if( scope.order === scope.by ) {
           scope.reverse = !scope.reverse 
        } else {
          scope.by = scope.order ;
          scope.reverse = false; 
        }
      }
    }
}
});