简体   繁体   中英

AngularJS: How to apply sort/reverse-sort to table having header populated by ng-repeat in angularjs

I have HTML part as shown below. I am populating th with ng-repeat. If anyone can please help me in how to sort and reverse-sort data by clicking on table columns. I tried this way but all columns access same property.

<div>
<table class="friends">
    <tr>
        <th ng-repeat="key in keys" ng-click="sortBy(propertyName)">{{key}}</th>
    </tr>
    <tr ng-repeat="friend in friends | orderBy:propertyName:reverse">
        <td ng-repeat="key in keys">{{friend[key]}}</td>
    </tr>
</table>

My Controller is as:

var 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}
];
$scope.keys = {
    first: "name",
    second: "phone",
    third: "age"
};


$scope.propertyName = 'age';
$scope.reverse = true;
$scope.friends = friends;

$scope.sortBy = function(propertyName) {
    $scope.reverse = ($scope.propertyName === propertyName) ?        !$scope.reverse : false;
    $scope.propertyName = propertyName;
};

You needed minor update in code. You need pass key in ng-click rather than propertyName

Here is working code. http://jsfiddle.net/halirgb/Lvc0u55v/

Below is modified line:

 <th ng-repeat="key in keys" ng-click="sortBy(key)">{{key}}</th>

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