Tuesday 24 February 2015

Sorting, Paging and Filter grid using AngularJS

In my previous tutorial I had discuss and explain about crud (create, read, update and delete) using mvc web api, angularjs  and bootstrap css.

Now I am going to explain that how can we achieve paging, sorting and filter in grid by using ng-table api of angularjs. In this article we will replace some code with previous tutorial so please download the code of previous article or you can follow the previous article in order to achieve.

Functionality we will achieve after doing this article:

1)      Paging.

2)      Sorting.

3)      Filtering.

Let’s start step by step so that we can achieve our objective at the end of this article. After completing this demo our application should look like this:

1)      Include this package in your existing application:

a)      ngTable

 It supports sorting, filtering and pagination. Header row with titles and filters automatic generated on compilation step.

2)      Add the highlighted reference in your Index.cshtml file. This will add the reference of ngTable api of angularjs in our application. After adding this only we can use its sorting, paging and filter features.

 

@{

    Layout = null;

}

 

<!DOCTYPE html>

 

<html ng-app="EmpApp">

<head>

    <meta name="viewport" content="width=device-width" />

    <title>Index</title>

    <link href="@Url.Content("~/Content/bootstrap.min.css")" rel="stylesheet" type="text/css" />

    <link href="@Url.Content("~/Content/ng-table.css")" rel="stylesheet" type="text/css" />

    <script src="@Url.Content("~/Scripts/angular.min.js")" type="text/javascript"></script>

    <script src="@Url.Content("~/Scripts/angular-route.js")" type="text/javascript"></script>

    <script src="@Url.Content("~/Scripts/ng-table.min.js")" type="text/javascript"></script>

    <script src="@Url.Content("~/Scripts/app/app.js")" type="text/javascript"></script>

    <script src="@Url.Content("~/Scripts/app/controller.js")" type="text/javascript"></script>

</head>

<body>

    <div class="main container" ng-view>

      

    </div>

</body>

</html>

 

3)      In list.html, replace the code with the following. I highlighted some of the changes part so it will be easy for us identity the code of functionalities given by this tutorial.

<div>

    <a href="#/create" class="btn">Create</a>

</div>

<div class="row">

    <div class="col-lg-offset-8 col-lg-4">

        <input type="text" class="form-control" placeholder="Search for..." ng-model="search" />

    </div>

</div>

<hr />

<div class="table-responsive">

    <p class="text-right">

        <strong>Page:</strong> {{tableParams.page()}}, <strong>Count per page:</strong>

        {{tableParams.count()}}</p>

    <table class="table table-striped table-bordered" ng-table="tableParams" template-pagination="custom/pager">

        <tr ng-repeat="item in $data | filter:search">

            <td data-title="'Employee Id'" sortable="'EmployeeId'">

                {{ item.EmployeeId }}

            </td>

            <td data-title="'First Name'" sortable="'FirstName'">

                {{ item.FirstName }}

            </td>

            <td data-title="'Last Name'" sortable="'LastName'">

                {{ item.LastName }}

            </td>

            <td data-title="'Description'">

                {{ item.Description }}

            </td>

            <td data-title="'Salary'" sortable="'Salary'">

                {{ item.Salary | number: 2 }}

            </td>

            <td data-title="'Country'" sortable="'Country'">

                {{ item.Country }}

            </td>

            <td data-title="'State'" sortable="'State'">

                {{ item.State }}

            </td>

            <td data-title="'Date of Birth'" sortable="'DateofBirth'">

                {{ item.DateofBirth | date }}

            </td>

            <td data-title="'Is Active'">

                <span class="label" ng-class="{true:'label-success', false:'label-danger', '':'hidden'}[item.IsActive]">

                    {{ item.IsActive ? 'Active' : 'In Active' }}</span>

            </td>

            <td>

                <a href="#/edit/{{item.EmployeeId}}" class="glyphicon glyphicon-edit"></a>

            </td>

            <td>

                <a href="#/delete/{{item.EmployeeId}}" class="glyphicon glyphicon-trash"></a>

            </td>

        </tr>

    </table>

    <script type="text/ng-template" id="custom/pager">

        <ul class="pager ng-cloak">

          <li ng-repeat="page in pages"

                ng-class="{'disabled': !page.active, 'previous': page.type == 'prev', 'next': page.type == 'next'}"

                ng-show="page.type == 'prev' || page.type == 'next'" ng-switch="page.type">

            <a ng-switch-when="prev" ng-click="params.page(page.number)" href="">&laquo; Previous</a>

            <a ng-switch-when="next" ng-click="params.page(page.number)" href="">Next &raquo;</a>

          </li>

            <li>

            <div class="btn-group">

                <button type="button" ng-class="{'active':params.count() == 5}" ng-click="params.count(5)" class="btn btn-default">5</button>

                <button type="button" ng-class="{'active':params.count() == 10}" ng-click="params.count(10)" class="btn btn-default">10</button>

                <button type="button" ng-class="{'active':params.count() == 20}" ng-click="params.count(20)" class="btn btn-default">20</button>

                <button type="button" ng-class="{'active':params.count() == 50}" ng-click="params.count(50)" class="btn btn-default">50</button>

            </div>

            </li>

        </ul>

    </script>

</div>

 

 

4)      In controller.js, only replace declaration section of EmpControllers and ListController definition.

var EmpControllers = angular.module("EmpControllers", ['ngTable']);

 

// this controller call the api method and display the list of employees

// in list.html

EmpControllers.controller("ListController", ['$scope', '$http', '$filter', 'ngTableParams',

    function ($scope, $http, $filter, ngTableParams) {

      

       $scope.headers = [

          { column: "FirstName" },

          { column: "LastName" }

        ];

 

        $http.get('/api/employee').success(function (data) {

 

            $scope.tableParams = new ngTableParams({

                page: 1,              // show first page

                count: 5,             // count per page

                sorting: {

                    EmployeeId: 'asc' // initial sorting

                }

            }, {

                total: data.length,

                getData: function($defer, params) {

                   

                    var orderedData = params.sorting() ?

                                $filter('orderBy')(data, params.orderBy()) :

                                data;

 

                    $defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count()));

                }

            });

        });

    }]

);

 

Thanks for reading this article. I hope this will help you. If having any suggestion and feedback please provide by using comment box.

12 comments:

Unknown said...

I want full code of this functionality

Rohit said...

Hi!

You can download from a link given below:
https://onedrive.live.com/embed?cid=A9F5007CD218E84F&resid=A9F5007CD218E84F%21139&authkey=ABTmNaynse7HSI0

Unknown said...

hello,
how to make search in whole data not in current page

Unknown said...

@salah Rzzaz Use ngTable module of angular js . For searching, filtering.

Please refer http://ng-table.com/#/

Unknown said...

Hello,
how to make a pagination as number like (1 - 2 - 3 -4)

Sridhar said...

Are we not going to do anything on server side for pagination?

Rohit said...

Hi Sridhar,

We can implement server side pagination also. If you like to enhance you can implement.

Anonymous said...

Sir need of database script file also to understant with debug mode, please provile database script also asap...

Unknown said...

we can implement easly thank you for sharing Angularjs Online Training

Richard Mendes said...

Hey this is also a nice post, Checkout this post as well, Angularjs CRUD with pagination, sorting, filtering with Codeigniter framework. Codeigniter setup is also shown in the blog. You can click on the download link and set up the project on your local machine as well. Cheers :)

https://angularjscrudpagination.blogspot.com/

Tejuteju said...

Thank you. Well it was the nice to post and very helpful information on AngularJS Online Training

Akhil C said...

This is really an awesome article. Thank you for sharing this.It is worth reading for everyone.
Hire Angularjs Developer in India