Introduction

Angular UI Grid is a data grid for AngularJS without JQuery that can perform with large data, which is part of the Angular UI suite.

Background

Recently, I was searching for a data table that have components like sorting, filtering, pagination, inline editor, responsive and other advanced facilities. I have tried to integrate & use Jquery datatable(Angular), but the problem arose while I was trying to pass entire row passing while row click/row selected button click.

It fails to pass angular object (only can pass int, string, boolean) while rendering, this was a big issue to me as I was using angularJS in the application's frontend.

I decided to change the entire table, I found Angular UI Grid.

Let’s Get Into It

As we know Angular UI Grid is a part of Angular UI, so we have some facilities. We need to download/install package before we are going to use in our application.

To download the package, go to URL,

grid

SQL Database

Let’s Create a SQL database, using the new database execute the table script to create new table in the new database.

  1. CREATE TABLE [dbo].[tblProducts](
  2. [ProductID] [int] NOT NULL,
  3. [ProductTitle] [nvarchar](256) NULL,
  4. [Type] [nvarchar](50) NULL,
  5. [Price] [numeric](18, 2) NULL,
  6. [CreatedOn] [datetime] NULL,
  7. CONSTRAINT [PK_tblProducts] PRIMARY KEY CLUSTERED
  8. (
  9. [ProductID] ASC
  10. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
  11. ) ON [PRIMARY]
  12. GO
Demo Data
  1. INSERT INTO [tblProducts]
  2. SELECT 1,'Ape Lifestyle Cotton Casual T-Shirt - Gray','Clothing',270.00,getdate()
  3. Union All
  4. SELECT 2,'Cotton Casual Short Sleeve Polo - White','Clothing',790.50,getdate()
  5. Union All
  6. SELECT 3,'Cotton Casual Shirt - Sky Blue and White Stripe','Clothing',1555.00,getdate()
  7. Union All
  8. SELECT 4,'Cotton Mix Casual Panjabi - Thistle and Gray Stripe','Clothing',2458.00,getdate()
  9. Union All
  10. SELECT 5,'Cotton Mix Casual Panjabi - Black and Purple Stripe','Clothing',2458.00,getdate()
  11. Union All
  12. SELECT 6,'Cotton Casual Shirt - Red and White Check','Clothing',1735.00,getdate()
  13. Union All
  14. SELECT 7,'Kingstar TITANS 1 i19 Smartphone 8GB - White','Smartphone',6300.00,getdate()
  15. Union All
  16. SELECT 8,'MyCell Spider A4 Smartphone 8GB – White','Smartphone',7770.00,getdate()
  17. Union All
  18. SELECT 9,'HTC One M9S Nano-SIM Smartphone 16GB - Silver','Smartphone',26900.00,getdate()
  19. Union All
  20. SELECT 10,'WE X1 Smartphone 16GB – Silver','Smartphone',18600.00,getdate()
  21. Union All
  22. SELECT 11,'Microsoft Lumia 540 Smartphone 8GB – Cyan','Smartphone',13999.00,getdate()
  23. Union All
  24. SELECT 12,'BlackBerry Z10 Smartphone 16GB - White','Smartphone',18000.00,getdate()
  25. Union All
  26. SELECT 13,'Ape Lifestyle Cotton Casual T-Shirt - Gray','Clothing',270.00,getdate()
  27. Union All
  28. SELECT 14,'Cotton Casual Short Sleeve Polo - White','Clothing',790.50,getdate()
  29. Union All
  30. SELECT 15,'Cotton Casual Shirt - Sky Blue and White Stripe','Clothing',1555.00,getdate()
  31. Union All
  32. SELECT 16,'Cotton Mix Casual Panjabi - Thistle and Gray Stripe','Clothing',2458.00,getdate()
  33. Union All
  34. SELECT 17,'Cotton Mix Casual Panjabi - Black and Purple Stripe','Clothing',2458.00,getdate()
  35. Union All
  36. SELECT 18,'Cotton Casual Shirt - Red and White Check','Clothing',1735.00,getdate()
  37. Union All
  38. SELECT 19,'Kingstar TITANS 1 i19 Smartphone 8GB - White','Smartphone',6300.00,getdate()
  39. Union All
  40. SELECT 20,'MyCell Spider A4 Smartphone 8GB – White','Smartphone',7770.00,getdate()
  41. Union All
  42. SELECT 21,'HTC One M9S Nano-SIM Smartphone 16GB - Silver','Smartphone',26900.00,getdate()
  43. Union All
  44. SELECT 22,'WE X1 Smartphone 16GB – Silver','Smartphone',18600.00,getdate()
  45. Union All
  46. SELECT 23,'Microsoft Lumia 540 Smartphone 8GB – Cyan','Smartphone',13999.00,getdate()
  47. Union All
  48. SELECT 24,'BlackBerry Z10 Smartphone 16GB - White','Smartphone',18000.00,getdate()
MVC Application

Let’s create a new demo application with visual studio 2015. Select MVC and Web API below. Click OK.

app

After loading the initial application template, we need to install the script packages. We need to install two packages using NuGet Package installer.

First we will install AngularJS and after that we need to add Angular-Ui-Grid. In package manager console write Install-Package angularjs. After successfully installation write Install-Package angular-ui-grid.

code

Or we can install packages using NuGet package manager,

angularJS

angularJS

angularJS-uigrid

angularJS

Our packages are installed, now we need to add a new controller and generate view to the application. In our master layout we need to add reference of script library.

library

In the head section add the ui style reference.

reference

AngularJS

Let’s add folders to create angular script.

create

JS-Module
  1. var app;
  2. (function () {
  3. 'use strict';
  4. app = angular.module('UIGrid_App',
  5. [
  6. 'ngAnimate', // support for CSS-based animations
  7. 'ngTouch', //for touch-enabled devices
  8. 'ui.grid', //data grid for AngularJS
  9. 'ui.grid.pagination', //data grid Pagination
  10. 'ui.grid.resizeColumns', //data grid Resize column
  11. 'ui.grid.moveColumns', //data grid Move column
  12. 'ui.grid.pinning', //data grid Pin column Left/Right
  13. 'ui.grid.selection', //data grid Select Rows
  14. 'ui.grid.autoResize', //data grid Enabled auto column Size
  15. 'ui.grid.exporter' //data grid Export Data
  16. ]);
  17. })();
JS-Controller
  1. app.controller('ProductsCtrl', ['$scope', 'CRUDService', 'uiGridConstants',
  2. function ($scope, CRUDService, uiGridConstants) {
  3. $scope.gridOptions = [];
  4. //Pagination
  5. $scope.pagination = {
  6. paginationPageSizes: [15, 25, 50, 75, 100, "All"],
  7. ddlpageSize: 15,
  8. pageNumber: 1,
  9. pageSize: 15,
  10. totalItems: 0,
  11. getTotalPages: function () {
  12. return Math.ceil(this.totalItems / this.pageSize);
  13. },
  14. pageSizeChange: function () {
  15. if (this.ddlpageSize == "All")
  16. this.pageSize = $scope.pagination.totalItems;
  17. else
  18. this.pageSize = this.ddlpageSize
  19. this.pageNumber = 1
  20. $scope.GetProducts();
  21. },
  22. firstPage: function () {
  23. if (this.pageNumber > 1) {
  24. this.pageNumber = 1
  25. $scope.GetProducts();
  26. }
  27. },
  28. nextPage: function () {
  29. if (this.pageNumber < this.getTotalPages()) {
  30. this.pageNumber++;
  31. $scope.GetProducts();
  32. }
  33. },
  34. previousPage: function () {
  35. if (this.pageNumber > 1) {
  36. this.pageNumber--;
  37. $scope.GetProducts();
  38. }
  39. },
  40. lastPage: function () {
  41. if (this.pageNumber >= 1) {
  42. this.pageNumber = this.getTotalPages();
  43. $scope.GetProducts();
  44. }
  45. }
  46. };
  47. //ui-Grid Call
  48. $scope.GetProducts = function () {
  49. $scope.loaderMore = true;
  50. $scope.lblMessage = 'loading please wait....!';
  51. $scope.result = "color-green";
  52. $scope.highlightFilteredHeader = function (row, rowRenderIndex, col, colRenderIndex) {
  53. if (col.filters[0].term) {
  54. return 'header-filtered';
  55. } else {
  56. return '';
  57. }
  58. };
  59. $scope.gridOptions = {
  60. useExternalPagination: true,
  61. useExternalSorting: true,
  62. enableFiltering: true,
  63. enableSorting: true,
  64. enableRowSelection: true,
  65. enableSelectAll: true,
  66. enableGridMenu: true,
  67. columnDefs: [
  68. { name: "ProductID", displayName: "Product ID", width: '10%', headerCellClass: $scope.highlightFilteredHeader },
  69. { name: "ProductTitle", title: "Product Title", width: '40%', headerCellClass: $scope.highlightFilteredHeader },
  70. { name: "Type", title: "Type", headerCellClass: $scope.highlightFilteredHeader },
  71. {
  72. name: "Price", title: "Price", cellFilter: 'number',
  73. filters: [{ condition: uiGridConstants.filter.GREATER_THAN, placeholder: 'Minimum' }, { condition: uiGridConstants.filter.LESS_THAN, placeholder: 'Maximum' }],
  74. headerCellClass: $scope.highlightFilteredHeader
  75. },
  76. { name: "CreatedOn", displayName: "Created On", cellFilter: 'date:"short"', headerCellClass: $scope.highlightFilteredHeader },
  77. {
  78. name: 'Edit',
  79. enableFiltering: false,
  80. enableSorting: false,
  81. width: '5%',
  82. enableColumnResizing: false,
  83. cellTemplate: '<span class="label label-warning label-mini">' +
  84. '<a href="" style="color:white" title="Select" ng-click="grid.appScope.GetByID(row.entity)">' +
  85. '<i class="fa fa-check-square" aria-hidden="true"></i>' +
  86. '</a>' +
  87. '</span>'
  88. }
  89. ],
  90. exporterAllDataFn: function () {
  91. return getPage(1, $scope.gridOptions.totalItems, paginationOptions.sort)
  92. .then(function () {
  93. $scope.gridOptions.useExternalPagination = false;
  94. $scope.gridOptions.useExternalSorting = false;
  95. getPage = null;
  96. });
  97. },
  98. };
  99. var NextPage = (($scope.pagination.pageNumber - 1) * $scope.pagination.pageSize);
  100. var NextPageSize = $scope.pagination.pageSize;
  101. var apiRoute = 'api/Product/GetProducts/' + NextPage + '/' + NextPageSize;
  102. var result = CRUDService.getProducts(apiRoute);
  103. result.then(
  104. function (response) {
  105. $scope.pagination.totalItems = response.data.recordsTotal;
  106. $scope.gridOptions.data = response.data.productList;
  107. $scope.loaderMore = false;
  108. },
  109. function (error) {
  110. console.log("Error: " + error);
  111. });
  112. }
  113. //Default Load
  114. $scope.GetProducts();
  115. //Selected Call
  116. $scope.GetByID = function (model) {
  117. $scope.SelectedRow = model;
  118. };
  119. }
  120. ]);
  121. JS-Service
  122. app.service('CRUDService', function ($http) {
  123. //**********----Get Record----***************
  124. this.getProducts = function (apiRoute) {
  125. return $http.get(apiRoute);
  126. }
  127. });
Ui-Grid

In index.cshtml page add ui-grid directive

directive

The loader which will show a loading messaging while data is loading from server.

server

At bottom end, add angular reference to the page

reference

Complete Ui Code
  1. @{
  2. ViewBag.Title = "Products";
  3. }
  4. <h3>Products with UI Grid</h3>
  5. <div class="row">
  6. <div class="col-md-12" ng-controller="ProductsCtrl">
  7. <div ui-grid="gridOptions"
  8. ui-grid-resize-columns
  9. ui-grid-move-columns
  10. ui-grid-exporter
  11. ui-grid-selection
  12. ui-grid-pinning class="grid"></div>
  13. <div class="loadmore">
  14. <div ng-show="loaderMore" ng-class="result">
  15. <img src="~/Content/ng-loader.gif" />
  16. {{lblMessage}}
  17. </div>
  18. </div>
  19. <div role="contentinfo" class="ui-grid-pager-panel ng-scope">
  20. <div role="navigation" class="ui-grid-pager-container">
  21. <div role="menubar" class="ui-grid-pager-control">
  22. <!-- Start Page -->
  23. <button type="button" role="menuitem" class="ui-grid-pager-first" ui-grid-one-bind-title="aria.pageToFirst"
  24. ui-grid-one-bind-aria-label="aria.pageToFirst"
  25. ng-click="pagination.firstPage()"
  26. ng-disabled="cantPageBackward()" title="Page to first" aria-label="Page to first"
  27. disabled="disabled">
  28. <div class="first-triangle">
  29. <div class="first-bar"></div>
  30. </div>
  31. </button>
  32. <!-- Prev Page -->
  33. <button type="button" role="menuitem" class="ui-grid-pager-previous"
  34. ui-grid-one-bind-title="aria.pageBack" ui-grid-one-bind-aria-label="aria.pageBack"
  35. ng-click="pagination.previousPage()"
  36. ng-disabled="cantPageBackward()" title="Page back" aria-label="Page back" disabled="disabled">
  37. <div class="first-triangle prev-triangle"></div>
  38. </button>
  39. <input type="number" ui-grid-one-bind-title="aria.pageSelected" ui-grid-one-bind-aria-label="aria.pageSelected"
  40. class="ui-grid-pager-control-input ng-pristine ng-untouched ng-valid ng-not-empty ng-valid-min ng-valid-max ng-valid-required"
  41. ng-model="pagination.pageNumber"
  42. min="1" max="{{pagination.getTotalPages()}}" required="" title="Selected page"
  43. aria-label="Selected page" disabled>
  44. <span class="ui-grid-pager-max-pages-number ng-binding"
  45. ng-show="pagination.getTotalPages() > 0">
  46. <abbr ui-grid-one-bind-title="paginationOf" title="of"> /</abbr>{{pagination.getTotalPages()}}
  47. </span>
  48. <!-- Next Page -->
  49. <button type="button" role="menuitem" class="ui-grid-pager-next" ui-grid-one-bind-title="aria.pageForward"
  50. ui-grid-one-bind-aria-label="aria.pageForward"
  51. ng-click="pagination.nextPage()"
  52. ng-disabled="cantPageForward()"
  53. title="Page forward" aria-label="Page forward">
  54. <div class="last-triangle next-triangle"></div>
  55. </button>
  56. <!-- Last Page -->
  57. <button type="button" role="menuitem" class="ui-grid-pager-last"
  58. ui-grid-one-bind-title="aria.pageToLast" ui-grid-one-bind-aria-label="aria.pageToLast"
  59. ng-click="pagination.lastPage()" ng-disabled="cantPageToLast()" title="Page to last" aria-label="Page to last">
  60. <div class="last-triangle"><div class="last-bar"></div></div>
  61. </button>
  62. </div><!-- ngIf: grid.options.paginationPageSizes.length > 1 -->
  63. <div class="ui-grid-pager-row-count-picker ng-scope" @*ng-if="pagination.ddlpageSize.length > 1"*@>
  64. <select ng-model="pagination.ddlpageSize"
  65. ng-options="o as o for o in pagination.paginationPageSizes" ng-change="pagination.pageSizeChange()"
  66. class="ng-pristine ng-untouched ng-valid ng-not-empty"></select>
  67. <span class="ui-grid-pager-row-count-label ng-binding"> items per page</span>
  68. </div>
  69. <!-- end ngIf: grid.options.paginationPageSizes.length > 1 -->
  70. <!-- ngIf: grid.options.paginationPageSizes.length <= 1 -->
  71. </div>
  72. <div class="ui-grid-pager-count-container">
  73. <div class="ui-grid-pager-count">
  74. <span ng-show="pagination.totalItems > 0" class="ng-binding">
  75. {{pagination.pageNumber}}<abbr ui-grid-one-bind-title="paginationThrough" title="through"> - </abbr>{{pagination.ddlpageSize}} of {{pagination.totalItems}} items
  76. </span>
  77. </div>
  78. </div>
  79. </div>
  80. <p>{{SelectedRow}}</p>
  81. </div>
  82. </div>
  83. @section AngularScript{
  84. <script src="~/ScriptsNg/Controllers/ProductsCtrl.js"></script>
  85. <script src="~/ScriptsNg/Service/CRUDService.js"></script>
  86. }
Model - Our Ui is ready Let’s create a new model in our demo application.

application

I have used api controller to get data from server, which will get called while pagination operates.

Api-Controller
  1. [RoutePrefix("api/Product")]
  2. public class ProductController : ApiController
  3. {
  4. private dbUIGrid_Entities _ctx = null;
  5. [HttpGet, ResponseType(typeof(tblProduct)), Route("GetProducts/{pageNumber:int}/{pageSize:int}")]
  6. public IHttpActionResult GetProducts(int pageNumber, int pageSize)
  7. {
  8. List<tblProduct> productList = null; int recordsTotal = 0;
  9. try
  10. {
  11. using (_ctx = new dbUIGrid_Entities())
  12. {
  13. recordsTotal = _ctx.tblProducts.Count();
  14. productList = _ctx.tblProducts.OrderBy(x => x.ProductID)
  15. .Skip(pageNumber)
  16. .Take(pageSize)
  17. .ToList();
  18. }
  19. }
  20. catch (Exception)
  21. {
  22. }
  23. return Json(new
  24. {
  25. recordsTotal,
  26. productList
  27. });
  28. }
  29. }
Final Output:

Output

Filter Data

Output

Hope this will help.