Home AngularJS - Sorting data ascending / descending when column is clicked
Reply: 3

AngularJS - Sorting data ascending / descending when column is clicked

Aly Al Ameen
1#
Aly Al Ameen Published in 2017-12-07 14:43:12Z

I have the following view code:

<tr ng-repeat="c in clients | orderBy:'code'">
    <td>{{c.firstname}} {{c.lastname}}</td>
    <td>{{c.telephone}}</td>
    <td>{{c.location}}</td>
    <td>{{c.code}}</td>
</tr>

I want to change the orderBy:'code' when column is clicked, assume that the user clicked on the column location, i want the orderBy condition to change to 'location' instead of code, and to be in this form

<tr ng-repeat="c in clients | orderBy:'location'">
Slava Utesinov
2#
Slava Utesinov Reply to 2017-12-08 07:48:55Z

angular.module('app', []).controller('ctrl', function($scope) {
  $scope.prefix = '+';
  $scope.sort = '';
  $scope.sortFn = function(name) {
    $scope.prefix = $scope.prefix == '-' ? '+' : '-';
    $scope.sort = $scope.prefix + name;
  }
  $scope.arrow = function(name){
    if($scope.sort.indexOf(name) != -1)
      return $scope.prefix == '+' ? '↑' : '↓';
    return '';
  }

  $scope.clients = [
    { name: 'Tom', age: 30 },
    { name: 'Max', age: 20 },
    { name: 'Sam', age: 40 },
    { name: 'Liza', age: 25 },
    { name: 'Henry', age: 35 }
  ]
})
table,
th,
td {
  border: 1px solid black;
  border-collapse: collapse;
}
th{
  cursor: pointer
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<table ng-app='app' ng-controller='ctrl'>
  <thead>
    <tr>      
      <th ng-click='sortFn("name")'>Name {{arrow("name")}}</th>
      <th ng-click='sortFn("age")'>Age {{arrow("age")}}</th>
    </tr>
  </thead>
  <tbody>
    <tr ng-repeat="c in clients | orderBy:sort">
      <td>{{c.name}}</td>
      <td>{{c.age}}</td>
    </tr>
  </tbody>
</table>

Sourabh MorwalGODtech
3#
Sourabh MorwalGODtech Reply to 2017-12-07 14:50:23Z

Use datatables.js for automate sorting https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css

https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js

Rakesh Burbure
4#
Rakesh Burbure Reply to 2017-12-07 19:23:45Z

write ng-click on the column and call a function like setSortByParameter and set the field sortBy.

and now write the orderBy as below.

<tr ng-repeat="c in clients | orderBy:'{{sortBy}}'">
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.311588 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO