It is a common requirement for any project to display data in a tabular format. The easiest way to do this is by using HTML tables, but soon this gets complex, you need a way to support sorting (single & multi columns), resizable columns, inline editing, filtering, pagination (client-side and server-side) and so on. There is a way to bind data to a HTML Table in AngularJs, but when it comes to sorting, paging, editing and dragging the columns, the grid choice is useful. ng-grid is Angular's native implementation of the Grid. There are many plugins from third-parties that can be integrated into AngularUI Pages, but ng-grid exists inside the AngularJs framework and is very rich in functionality and compatibility.

Let us create a sample ng-grid and understand how ng-grid works.

Example-1

  1. <!DOCTYPE html>
  2. <html ng-app="myApp">
  3. <head>
  4. <title>NG Grid Demo</title>
  5. <>
  6. .gridStyle
  7. {
  8. border: 5px solid #d4d4d4;
  9. width: 400px;
  10. height: 200px;
  11. }
  12. </style>
  13. <link rel="stylesheet" type="text/css" href="http://angular-ui.github.com/ng-grid/css/ng-grid.css" />
  14. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
  15. <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.min.js"></script>
  16. <script type="text/javascript" src="http://angular-ui.github.com/ng-grid/lib/ng-grid.debug.js"></script>
  17. <script type="text/javascript">
  18. var app = angular.module('myApp', ['ngGrid']);
  19. app.controller('MyCtrl', function ($scope) {
  20. $scope.Data = [{ Name: "Sachin", Skill: "ASP.NET" ,location:"Delhi"},
  21. { Name: "Ramesh", Skill: "C#.NET, VB", location: "Chenai" },
  22. { Name: "Pradeep", Skill: "ASP.NET MVC", location: "Bangalore" },
  23. { Name: "Manas", Skill: "SQL Server", location: "Chenai" },
  24. { Name: "Sachin", Skill: "ASP.NET", location: "Bangalore" }, ];
  25. $scope.gridOptions = { data: 'Data' };
  26. });
  27. </script>
  28. </head>
  29. <body ng-controller="MyCtrl">
  30. <div>
  31. <labl><b> Sample Demo to NG Grid</b></labl>
  32. </div>
  33. <div class="gridStyle" ng-grid="gridOptions"></div>
  34. </body>
  35. </html>

Output

There are four steps to show a sample grid, if we observe the preceding code.

Passed "ngGrid" as dependency to the module

  1. var app = angular.module('myApp', ['ngGrid']);

Assign some data to scope

  1. [{Name: "Sachin", Skill: "ASP.NET" ,location:"Delhi"},];

Set the data of the scope to gridOptions as

  1. $scope.gridOptions = {data: ‘Data’};

It is like assigning a datasource to nggrid, similar to Gridview1.datasource=dataset in ASP.NET.

Bind the data to the page

  1. <div class="gridStyle" ng-grid="gridOptions"></div>

It is like binding data to a GridView, similar to Gridview1.dataBind() in ASP.NET.

Don't forget to add the scripts and styles needed for ng-grid in the head section of the code.

Let us create a DB and Bind data to ng-grid by web API calls.

Example-2

Step 1

Let us create an Employee Table.

Step 2

We will create a web API that will return the employee data.

  1. public class EmployeeAPIController : ApiController
  2. {
  3. private EmployeeEntities db = new EmployeeEntities();
  4. public IEnumerable<Employee> GetEmployees()
  5. {
  6. return db.Employees.AsEnumerable();
  7. }
  8. }

Step 3

Add module service controller and html code.

Module

  1. var app;
  2. (function () {
  3. app = angular.module("EmployeeModule", ['ngGrid']);
  4. })();

Service

  1. app.service('EmployeeService', function ($http) {
  2. this.getAllEmployee = function () {
  3. return $http.get("/api/EmployeeAPI");
  4. }
  5. });

Controller

  1. app.controller('EmployeeController', function ($scope, EmployeeService) {
  2. GetAllRecords();
  3. function GetAllRecords() {
  4. var promiseGet = EmployeeService.getAllEmployee();
  5. promiseGet.then(function (pl) { $scope.Employees = pl.data, $scope.Data=pl.data },
  6. function (errorPl) {
  7. $log.error('Some Error in Getting Records.', errorPl);
  8. });
  9. }
  10. $scope.gridOptions = { data: 'Data' };
  11. });

Index.html

  1. <html data-ng-app="EmployeeModule">
  2. <head>
  3. <style type="text/css">
  4. .gridStyle
  5. {
  6. border: 5px solid #d4d4d4;
  7. width: 1000px;
  8. height: 200px;
  9. }
  10. </style>
  11. </head>
  12. <body data-ng-controller="EmployeeController">
  13. <div class="gridStyle" ng-grid="gridOptions"></div>
  14. </body>
  15. </html>
  16. <script src="~/Scripts/angular.js"></script>
  17. <script src="~/Scripts/EmployeeScripts/Module.js"></script>
  18. <script src="~/Scripts/EmployeeScripts/Service.js"></script>
  19. <script src="~/Scripts/EmployeeScripts/Controller.js"></script>
  20. <link rel="stylesheet" type="text/css" href="http://angular-ui.github.com/ng-grid/css/ng-grid.css" />
  21. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
  22. <script type="text/javascript" src="http://angular-ui.github.com/ng-grid/lib/ng-grid.debug.js"></script>

Output


Now, we have seen data from the database and binding to an ng-grid. Let us see now what the features are in ng-grid to make it more useful. We will do a sample ng-grid binding, editing, paging, sorting and grouping the records.

Example-3

  1. <!DOCTYPE html>
  2. <html ng-app="myApp">
  3. <head>
  4. <meta charset="utf-8" />
  5. <title>Working With NG-Grid </title>
  6. <style type="text/css">
  7. .gridStyle
  8. {
  9. border: 1px solid rgb(212, 212, 212);
  10. width: 800px;
  11. height: 370px;
  12. margin-left: 50px;
  13. color: coral;
  14. }
  15. .red {
  16. background-color: green;
  17. color: red;
  18. }
  19. </style>
  20. <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js"></script>
  21. <link rel="stylesheet" type="text/css" href="http://angular-ui.github.com/ng-grid/css/ng-grid.css" />
  22. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
  23. <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.min.js"></script>
  24. <script type="text/javascript" src="http://angular-ui.github.com/ng-grid/lib/ng-grid.debug.js"></script>
  25. <script>
  26. var app = angular.module('myApp', ['ngGrid']);
  27. app.controller(
  28. 'MyCtrl',
  29. function ($scope) {
  30. var Company;
  31. var Model;
  32. var Price;
  33. var Stocks;
  34. var x;
  35. $scope.submit = function () {
  36. Company = $scope.Company;
  37. Model = $scope.Model;
  38. Price = $scope.Price;
  39. Stocks = $scope.Stocks;
  40. $scope.myData.push({
  41. Company: Company,
  42. Model: Model,
  43. Price: Price,
  44. Stocks: Stocks
  45. });
  46. };
  47. $scope.myData = [{ "Company": "Samsung", "Model": "Samsung Galaxy Grand 2", "Price": 5000, "Stocks": 4 },
  48. { "Company": "Samsung", "Model": "Samsung Galaxy S3 Neo", "Price": 9000, "Stocks": 41 },
  49. { "Company": "Samsung", "Model": "Samsung Galaxy Grand Max", "Price": 11000, "Stocks": 4 },
  50. { "Company": "MicroMax", "Model": "Micromax Canvas Blaze", "Price": 6300, "Stocks": 0 },
  51. { "Company": "MicroMax", "Model": "Micromax Canvas Duddle", "Price": 11000, "Stocks": 3 },
  52. { "Company": "MicroMax", "Model": "Micromax Canvas Duddle- SPL", "Price": 11000, "Stocks": 3 },
  53. { "Company": "Blackberry", "Model": "Blackberry Z30", "Price": 19000, "Stocks": 10 },
  54. { "Company": "Blackberry", "Model": "Micromax bold 9780", "Price": 12900, "Stocks": 20 },
  55. ],
  56. $scope.gridOptions = {
  57. data: 'myData',
  58. pagingOptions: $scope.pagingOptions,
  59. enablePinning: true,
  60. enablePaging: true,
  61. showFooter: true,
  62. enableColumnResize: true,
  63. enableCellSelection: true,
  64. columnDefs: [
  65. {
  66. field: "Company",
  67. width: 180,
  68. pinned: true,
  69. enableCellEdit: true
  70. },
  71. {
  72. field: "Model",
  73. width: 200,
  74. enableCellEdit: true
  75. },
  76. {
  77. field: "Price",
  78. width: 100,
  79. enableCellEdit: true
  80. },
  81. {
  82. field: "Stocks",
  83. width: 120,
  84. enableCellEdit: true,
  85. cellTemplate: basicCellTemplate
  86. },
  87. {
  88. field: "Action",
  89. width: 200,
  90. enableCellEdit: false,
  91. cellTemplate: '<button id="editBtn" type="button" class="btn btn-xs btn-info" ng-click="updateCell()" >Click a Cell for Edit </button>'
  92. }]
  93. };
  94. $scope.selectedCell;
  95. $scope.selectedRow;
  96. $scope.selectedColumn;
  97. $scope.editCell = function (row, cell, column) {
  98. $scope.selectedCell = cell;
  99. $scope.selectedRow = row;
  100. $scope.selectedColumn = column;
  101. };
  102. $scope.updateCell = function () {
  103. // alert("checking");
  104. $scope.selectedRow[$scope.selectedColumn] = $scope.selectedCell;
  105. };
  106. var basicCellTemplate = '<div class="ngCellText" ng-class="col.colIndex()" ng-click="editCell(row.entity, row.getProperty(col.field), col.field)"><span class="ui-disableSelection hover">{{row.getProperty(col.field)}}</span></div>';
  107. $scope.filterOptions = {
  108. filterText: "",
  109. useExternalFilter: true
  110. };
  111. $scope.gridOptions.sortInfo = {
  112. fields: ['Company', 'Price'],
  113. directions: ['asc'],
  114. columns: [0, 1]
  115. };
  116. $scope.totalServerItems = 0;
  117. $scope.pagingOptions = {
  118. pageSizes: [5, 10, 20],
  119. pageSize: 5,
  120. currentPage: 1
  121. };
  122. $scope.changeGroupBy = function (group1, group2) {
  123. $scope.gridOptions.$gridScope.configGroups = [];
  124. $scope.gridOptions.$gridScope.configGroups.push(group1);
  125. $scope.gridOptions.$gridScope.configGroups.push(group2);
  126. $scope.gridOptions.groupBy();
  127. }
  128. $scope.clearGroupBy = function () {
  129. $scope.gridOptions.$gridScope.configGroups = [];
  130. $scope.gridOptions.groupBy();
  131. }
  132. });
  133. </script>
  134. </head>
  135. <body ng-controller="MyCtrl">
  136. <div class="panel panel-danger">
  137. <div class="panel-heading"></div>
  138. <div class="panel-body">
  139. <form class="input" ng-submit="submit()" role="form">
  140. <div style="border: 2px solid gray;width:600px;" >
  141. <labl> <b> Add a New Model: NG GRID DEMO </b></labl>
  142. <div class="form-group">
  143. <label"><b>Company:</b></label>
  144. <input id="inputs" class="form-control" type="text" ng-model="Company">
  145. </div>
  146. <div class="form-group">
  147. <label><b>Model :</b></label>
  148. <input id="Number1" class="form-control" type="text" ng-model="Model">
  149. </div>
  150. <div class="form-group">
  151. <label>Price</label>
  152. <input id="Date1" class="form-control" type="number" ng-model="Price">
  153. </div>
  154. <div class="form-group">
  155. <label>Stocks</label>
  156. <input id="Number2" class="form-control" type="number" ng-model="Stocks">
  157. </div>
  158. <div class="form-group">
  159. <input
  160. type="submit" value="submit" id="but" class="btn btn-success">
  161. <button type="button" ng-click="changeGroupBy('Company','Price')">Company By Name and Price</button>
  162. <button type="button" ng-click="clearGroupBy()">Clear Group</button>
  163. </div>
  164. </div>
  165. </form>
  166. </div>
  167. </div>
  168. <div class="panel panel-danger">
  169. <div class="panel-heading"><b><p style="padding-left:50px;">Model and Stocks Information</p></b></div>
  170. <div style="width: 500px;">
  171. <div class="gridStyle" ng-grid="gridOptions"></div>
  172. </div>
  173. </div>
  174. </body>
  175. </html>

Output

When doing a grouping, the screen arranges the grouping by Name and Price.

Code Explanation

Added data to scope

  1. $scope.myData = [{ "Company": "Samsung", "Model": "Samsung Galaxy Grand 2", "Price": 5000, "Stocks": 4 },
  2. { "Company": "Samsung", "Model": "Samsung Galaxy S3 Neo", "Price": 9000, "Stocks": 41 },
  3. { "Company": "Samsung", "Model": "Samsung Galaxy Grand Max", "Price": 11000, "Stocks": 4 },
  4. { "Company": "MicroMax", "Model": "Micromax Canvas Blaze", "Price": 6300, "Stocks": 0 },
  5. { "Company": "MicroMax", "Model": "Micromax Canvas Duddle", "Price": 11000, "Stocks": 3 },
  6. { "Company": "MicroMax", "Model": "Micromax Canvas Duddle- SPL", "Price": 11000, "Stocks": 3 },
  7. { "Company": "Blackberry", "Model": "Blackberry Z30", "Price": 19000, "Stocks": 10 },
  8. { "Company": "Blackberry", "Model": "Micromax bold 9780", "Price": 12900, "Stocks": 20 },
  9. ],

We can add a different property to ng-grid, such as paging, sorting, pinning of columns we need to display, enable scrolling and controlling a cell property value such as styling and events.

  1. $scope.gridOptions = {
  2. data: 'myData',
  3. pagingOptions: $scope.pagingOptions,
  4. enablePinning: true,
  5. enablePaging: true,
  6. showFooter: true,
  7. enableColumnResize: true,
  8. enableCellSelection: true,
  9. columnDefs: [
  10. {
  11. field: "Company",
  12. width: 180,
  13. pinned: true,
  14. enableCellEdit: true
  15. },
  16. {
  17. field: "Model",
  18. width: 200,
  19. enableCellEdit: true
  20. },
  21. {
  22. field: "Price",
  23. width: 100,
  24. enableCellEdit: true
  25. },
  26. {
  27. field: "Stocks",
  28. width: 120,
  29. enableCellEdit: true,
  30. cellTemplate: basicCellTemplate
  31. },
  32. {
  33. field: "Action",
  34. width: 200,
  35. enableCellEdit: false,
  36. cellTemplate: '<button id="editBtn" type="button" class="btn btn-xs btn-info" ng-click="updateCell()" >Click a Cell for Edit </button>'
  37. }]
  38. };

Added the cell edit code on scope

  1. var basicCellTemplate = '<div class="ngCellText" ng-class="col.colIndex()" ng-click="editCell(row.entity, row.getProperty(col.field), col.field)"><span class="ui-disableSelection hover">{{row.getProperty(col.field)}}</span></div>';

Added the grouping code on scope and calling it on click of “CompanyByName and Price” button.

  1. $scope.changeGroupBy = function (group1, group2) {
  2. $scope.gridOptions.$gridScope.configGroups = [];
  3. $scope.gridOptions.$gridScope.configGroups.push(group1);
  4. $scope.gridOptions.$gridScope.configGroups.push(group2);
  5. $scope.gridOptions.groupBy();
  6. }

This is all about the basics of ng-grid. I hope you have understood what ng-grid is and how to use it. Thanks for reading.