hide columns in ng-grid AngularJS

In this post you are going to learn how to hide specific columns in ng-grid (or) how to show only specific columns in ng-grid in AngularJS.

Please read my previous post on ng-grid to understand this post easily: ng-grid in AngularJS

Consider you have the following HTML code

<html ng-app="myApp">  
<head>
<title>My ngGrid Demo</title>  
<link rel="stylesheet" type="text/css" href="ng-grid.css" />
<link rel="stylesheet" type="text/css" href="myAppstyle.css" />
<script type="text/javascript" src="jquery-1.8.2.js"></script>
<script type="text/javascript" src="angular.js"></script>
<script type="text/javascript" src="ng-grid-1.3.2.js"></script>
<script type="text/javascript" src="app.js"></script>
</head>
<body ng-controller="MyngGridCtrl">
<div class="ngGridStyle" ng-grid="myGrid">
</div> 
</body>
</html>

and the required AngularJS code to show the ng-grid is

var myAppRoot = angular.module('myApp', ['ngGrid']);
 
myAppRoot.controller('MyngGridCtrl'function ($scope) {
    $scope.myData = [{ ID: 1, FirstName: 'John', LastName: 'somename', Country: 'USA' },
                   { ID: 2, FirstName: 'Sachin', LastName: 'somename', Country: 'India' },
                  { ID: 3, FirstName: 'Smith', LastName: 'somename', Country: 'UK' }
    ];
 
    $scope.myGrid = { data: 'myData' };
});

But when you use the above code, all the columns in $scope.myData object will be showed in the grid. If you want to show only specific columns then use the following code.

Let us say, you want to show only FirstName and LastName, then change the code of ng-grid like below

$scope.myGrid = {
    data: 'myData',
    columnDefs: [
           { field: 'FirstName', displayName: 'MyFirstName' },
           { field: 'LastName', displayName: 'MyLastName' },
    ]
};

The above code shows only FirstName and LastName columns and hides all the remaining columns.

In this way you can show specific columns in ng-grid. Hope it helps you. 

No comments:

Post a Comment