Search code examples
javascripthtmlangularjssortingcolumnsorting

Sorting the table data using angular js


I am trying to sort the table data based on the column "Submitted Date" . I have written some code but it doesn't seem to be working. As I am new to Angular JS I need some guidance here. Please help.

code:

Angular js:

 vm.sotData = function (column) {
        vm.reverseSort = (vm.sortColumn == column) ? !vm.reverseSort : false;
        vm.sortColumn = column;
    }

Html Code:

<th style="width:13%" ng-click="">Total Amt<span ng-class=""></span></th>
<th style="width:7%" ng-click="">Status<span ng-class=""></span></th>
<th style="width:7%" ng-click="vm.sotData('SubmittedDate')">Submitted Date
       <span ng-class="vm.getSortClass('SubmittedDate')"></span>
</th>

Solution

  • The main key of writing sorting functionality is to use

    {{ orderBy_expression | orderBy : expression : reverse  }}
    

    This returns a sorted Array based on the item. You can change the sorting order by specifying the reverse parameter.

    Let's take the example of below array

    $scope.friends = [
      {sno:1,name:'Yogesh Singh',age:23,gender:'Male'},
      {sno:2,name:'Sonarika Bhadoria',age:23,gender:'Female'},
      {sno:3,name:'Vishal Sahu',age:24,gender:'Male'},
      {sno:4,name:'Sanjay Singh',age:22,gender:'Male'}
    ];
    
    // column to sort
    $scope.column = 'sno';
    
    // sort ordering (Ascending or Descending). Set true for descending
    $scope.reverse = false; 
    
    // called on header click
    $scope.sortColumn = function(col){
      $scope.column = col;
      if($scope.reverse){
       $scope.reverse = false;
       $scope.reverseclass = 'arrow-up';
      }else{
       $scope.reverse = true;
       $scope.reverseclass = 'arrow-down';
      }
    }; 
    
     // remove and change class
    $scope.sortClass = function(col){
      if($scope.column == col ){
       if($scope.reverse){
        return 'arrow-down'; 
       }else{
        return 'arrow-up';
       }
      }else{
       return '';
      }
     };
    

    In html reverse is used for detecting ascending or descending ordering. The default value set to false for ascending.

    <table border='1'>
       <tr >
        <th ng-click='sortColumn("sno")' ng-class='sortClass("sno")'>S.no</th>
        <th ng-click='sortColumn("name")' ng-class='sortClass("name")'>Name</th>
        <th ng-click='sortColumn("age")' ng-class='sortClass("age")'>Age</th>
        <th ng-click='sortColumn("gender")' ng-class='sortClass("gender")'>Gender</th>
       </tr>
       <tr ng-repeat='friend in friends|orderBy:column:reverse'>
        <td width='20%' align='center'>{{friend.sno}}</td>
        <td width='35%' align='center'>{{friend.name}}</td>
        <td width='20%' align='center'>{{friend.age}}</td>
        <td width='25%' align='center'>{{friend.gender}}</td>
       </tr>
      </table>