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">
    <script src=""></script>
    <link rel="stylesheet" href="">
 <meta charset="utf-8" />
<body >
<div class="container" ng-controller="userCtrl">
    <h2>Angular sorting</h2>
    <div class="row">
        <table class="table table-bordered table-striped table-hover">
                <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 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>
            <tr ng-repeat="users in Users |orderBy:sortKey:reverse">


    //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



No comments:

Post a Comment