Monday, September 21, 2015

Angular Sorting table

                     
We can easily implement sorting functionality in a table as shown below. 

  • On ng-click we need to perform sort operation on the selected column
  • We need to use ng-show to show the image
  • We need to specify the order by in ng-repeat directive
  • Need a java script function for reverse as shown below
Edit in plunker




<!DOCTYPE html>
<html ng-app="myApp">
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
 <meta charset="utf-8" />
</head>
<body >
<div class="container" ng-controller="userCtrl">
    <h2>Angular sorting</h2>
    <div class="row">
        <table class="table table-bordered table-striped table-hover">
            <thead>
            <tr>
                <th ng-click="sort('StudentNo')">
                    Student No
                    <span class="glyphicon sort-icon" ng-show="sortKey=='StudentNo'" ng-class="{'glyphicon-chevron-up':reverse,'glyphicon-chevron-down':!reverse}"></span>
                </th>
                <th ng-click="sort('FirstName')">
                    First Name
                    <span class="glyphicon sort-icon" ng-show="sortKey=='FirstName'" ng-class="{'glyphicon-chevron-up':reverse,'glyphicon-chevron-down':!reverse}"></span>
                </th>
               </tr>
            </thead>
            <tbody>
            <tr ng-repeat="users in Users |orderBy:sortKey:reverse">
                <td>{{users.StudentNo}}</td>
                <td>{{users.FirstName}}</td>
             </tr>
            </tbody>
        </table>
    </div>
</div>
</body>
</html>

Script




<script>
    //declare a module
    var myAppModule = angular.module('myApp', []);
    myAppModule.controller('userCtrl', function ($scope) {
        $scope.Users =
        [
             { "StudentNo": "1", "FirstName": "Prathap"},
             { "StudentNo": "2","FirstName": "John"},
             { "StudentNo": "3","FirstName": "Peter"}

        ];
        //Function for sorting
        $scope.sort = function(keyname) {
            $scope.sortKey = keyname; //set the sortKey to the param passed
            $scope.reverse = !$scope.reverse; //if true make it false and vice versa
        };
    });
</script>

Output


Output

No comments:

Post a Comment