How to reverse sort a column on click using AngularJS - cSharp Coder

Latest

cSharp Coder

Sharp Future

Monday, September 14, 2020

How to reverse sort a column on click using AngularJS

 I have a simple method of sorting the table column implemented 


In the html

change the ng-click to call a function

<tr>
    <th><a ng-click="sortProperty('a')">Status</a></th>
    <th><a ng-click="sortProperty('b')">Ref</a></th>
    <th><a ng-click="sortProperty('c')">Service</a></th>
    <th><a ng-click="sortProperty('d')">Domain</a></th>
    <th><a ng-click="sortProperty('e')">Service Owner</a></th>
    <th><a ng-click="sortProperty('f')">Stage</a></th>
</tr>

In the Javascript:

add a '+' to the orderProperty variable

$scope.orderProperty = "+f";

then add this function

$scope.sortProperty = function(column) {
    var currentColumn = $scope.orderProperty.slice(1);
    var currentDirection = $scope.orderProperty.slice(0, 1);
    var dir = '+';

    if (column === currentColumn) {
        dir = currentDirection === '+' ? '-' : '+';
    }
    $scope.orderProperty = dir + column;
};

Clicking on the column header will now toggle the sort

see JsFiddle demo

No comments:

Post a Comment