user6579134 user6579134 - 1 year ago 67
HTML Question

sort by names in a list in ascending order onclick with angularjs

I populate brief info about customers in a table from a web api. What i want to achieve is when someone should click on the

Customer Name
text, the names there should be order in ascending order and on another click it should toggle to descending. By default when the page loads it arranges the list by ID descending

HTML

<table class="table table-striped table-hover">
<tr class="success">
<td><strong><a href="#">Customer Name</a></strong></td>
<td><strong>Phone Number</strong></td>
<td><strong>Address</strong></td>
<td><strong>Gender</strong></td>
<td><strong>Email</strong></td>
<td><strong>User Group</strong></td>
</tr>
<tr ng-repeat="item in users_list | orderBy:'-ID'">
<td>{{item.Customer_Name}}</td>
<td>{{item.Phone_Number}}</td>
<td>{{item.Address}}</td>
<td>{{item.gender}}</td>
<td>{{item.email}}</td>
<td>{{item.user_group}}</td>
</tr>
</table>


JS

.controller('app_users_ctrl',function($scope,$http,$location){
$scope.loading=true;
$http.post('http://localhost/calls/app_users.php').success(function(data){
$scope.users_list=data
console.log(JSON.stringify(data));
$scope.loading=false;
})
})

Answer Source

Hi have you tired something like:

<table class="table table-striped table-hover">
  <tr class="success">
    <td><strong><a clikme('Customer_Name')>Customer Name</a></strong></td>
    <td><strong><a clikme('Phone_Number')>Phone Number</a></strong></td>
    <td><strong>Address</strong></td>
    <td><strong>Gender</strong></td>
    <td><strong>Email</strong></td>
    <td><strong>User Group</strong></td>
  </tr>
  <tr ng-repeat="item in users_list | orderBy: myvar">
    <td >{{item.Customer_Name}}</td>
    <td >{{item.Phone_Number}}</td>
    <td>{{item.Address}}</td>
    <td>{{item.gender}}</td>
    <td>{{item.email}}</td>
    <td>{{item.user_group}}</td>
  </tr>
  </table>

and the in you js:

.controller('app_users_ctrl',function($scope,$http,$location){
    $scope.loading=true;
    var order = false;

$http.post('http://localhost/calls/app_users.php').success(function(data){
    $scope.users_list=data
    console.log(JSON.stringify(data));
    $scope.loading=false;
        })
    })

$scope.clikme= function(field){

 $scope.myvar= order ? '-' + field : '+' + field;
order=!order;
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download