简体   繁体   中英

AngularJS - Sorting data ascending / descending when column is clicked

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'">

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}}'">

 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM