Using Ng-grid in AngularUI Pages

This article explains the usage of ng-grid in AngularJS.

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.          
  5.         public IEnumerable<Employee> GetEmployees()  
  6.         {  
  7.             return db.Employees.AsEnumerable();  
  8.         }  
  9.     }  

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.   
  3.     this.getAllEmployee = function () {  
  4.         return $http.get("/api/EmployeeAPI");  
  5.     }  
  6. });  

Controller

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

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

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

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.   
  3. $scope.gridOptions.$gridScope.configGroups = [];  
  4.   
  5. $scope.gridOptions.$gridScope.configGroups.push(group1);  
  6.   
  7. $scope.gridOptions.$gridScope.configGroups.push(group2);  
  8.   
  9. $scope.gridOptions.groupBy();  
  10.   
  11. }  

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.