You are here: Home » Angular js » Sorting table data in Angular js

Sorting table data in Angular js

0 Flares 0 Flares ×

To sorting table data in Angular js, first call a function on table column click, you may name it as you wish. Here i am naming it “changeOrder”. Use “| orderBy:!changeOrder?’-name’:’country'” in ng-repeat. “-” denote desc order. Here we define default order by name desc.

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>

<p>Click the columns name to change the sorting order:</p>

<div ng-app="myApp" ng-controller="namesCtrl">

<table border="1" width="100%">
<tr>
<th ng-click="changeOrder=!changeOrder">Name</th>
<th ng-click="changeOrder=!changeOrder">Country</th>

</tr>
<tr ng-repeat="x in names | orderBy:!changeOrder?'-name':'country'">
<td>{{x.name}}</td>
<td>{{x.country}}</td>
</tr>
</table>

</div>

<script>
angular.module('myApp', []).controller('namesCtrl', function($scope) {
    $scope.names = [
        {name:'Abhishek Sinha',country:'India'},
        {name:'Md Sakeel',country:'Pakistan'},
        {name:'Algel ',country:'England'},
        {name:'Chand',country:'India'},
        {name:'Joe',country:'Denmark'},
        {name:'Rustin',country:'Sweden'},
        ];
    $scope.orderByMe = function(x) {
        $scope.myOrderBy = x;
    }
});
</script>

</body>
</html>


In above example, we are taking static data, we can use web service for dynamic data. Use below code for dynamic data. Here i am created a web service in customers.php and call it.

<script>
var app = angular.module('myApp', []);
app.controller('namesCtrl', function($scope, $http) {
    $http.get("http://www.phpsage.com/angular/customers.php")
    .then(function (response) {$scope.names = response.data.records;});
});
</script>

Click to view demo

About Abhishek Sinha

I am Abhishek and I love to code on PHP.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

Scroll To Top
0 Flares Twitter 0 Facebook 0 Google+ 0 StumbleUpon 0 Pin It Share 0 LinkedIn 0 0 Flares ×