CalebG
CalebG

Reputation: 283

ng-grid Auto / Dynamic Height

How do I get ng-grid to auto resize its height based on the page size? The documentation on ng-grid's site uses a fixed height. The best solution I've seen comes from this link:

.ngViewport.ng-scope {
    height: auto !important;
    overflow-y: hidden;
}

.ngTopPanel.ng-scope, .ngHeaderContainer {
    width: auto !important;
}

This does not work with server-side paging. I've copied the server-side paging example from ng-grid's site, and applied the css above, but as you can see, only the first 6 rows are shown: http://plnkr.co/edit/d9t5JvebRjUxZoHNqD7K?p=preview

And { height: 100% } does not work...

Upvotes: 20

Views: 32318

Answers (7)

Belter
Belter

Reputation: 3807

I think I solved this problem perfectly after 48 hours,

var app = angular.module('app', ['ngTouch', 'ui.grid', 'ui.grid.pagination', 'ui.grid.autoResize']);

app.controller('MainCtrl', ['$scope', '$http', '$interval', function($scope, $http, $interval) {

  var paginationOptions = {
    pageNumber: 1,
    pageSize: 20,
  };
  $scope.currentPage = 1;
  $scope.pageSize = paginationOptions.pageSize;
  $scope.gridOptions = {
    rowHeight: 30,
    enableSorting: true,
    paginationPageSizes: [$scope.pageSize, $scope.pageSize * 2, $scope.pageSize * 3],
    paginationPageSize: paginationOptions.pageSize,
    columnDefs: [{
      name: 'name'
    }, {
      name: 'gender',
      enableSorting: false
    }, {
      name: 'company',
      enableSorting: false
    }],
    onRegisterApi: function(gridApi) {
      $scope.gridApi = gridApi;
      gridApi.pagination.on.paginationChanged($scope, function(newPage, pageSize) {
        paginationOptions.pageNumber = newPage;
        paginationOptions.pageSize = pageSize;
        $scope.pageSize = pageSize;
        $scope.currentPage = newPage;
        $scope.totalPage = Math.ceil($scope.gridOptions.totalItems / $scope.pageSize);
      });
    }
  };

  var loadData = function() {
    var url = 'https://cdn.rawgit.com/angular-ui/ui-grid.info/gh-pages/data/100.json';
    $http.get(url)
      .success(function(data) {
        $scope.gridOptions.totalItems = data.length;
        $scope.totalPage = Math.ceil($scope.gridOptions.totalItems / $scope.pageSize);
        $scope.gridOptions.data = data;
      });
  };

  loadData();

  // for resize grid's height
  $scope.tableHeight = 'height: 600px';

  function getTableHeight(totalPage, currentPage, pageSize, dataLen) {
    var rowHeight = 30; // row height
    var headerHeight = 50; // header height
    var footerHeight = 60; // bottom scroll bar height
    var totalH = 0;
    if (totalPage > 1) {
      // console.log('hehehehe');
      if (currentPage < totalPage) {
        totalH = pageSize * rowHeight + headerHeight + footerHeight;
      } else {
        var lastPageSize = dataLen % pageSize;
        // console.log(lastPageSize);
        if (lastPageSize === 0) {
          totalH = pageSize * rowHeight + headerHeight + footerHeight;
        } else {
          totalH = lastPageSize * rowHeight + headerHeight + footerHeight;
        }
      }
      console.log(totalH);
    } else {
      totalH = dataLen * rowHeight + headerHeight + footerHeight;
    }
    return 'height: ' + (totalH) + 'px';
  }

  $interval(function() {
    $scope.tableHeight = getTableHeight($scope.totalPage,
      $scope.currentPage, $scope.pageSize,
      $scope.gridOptions.data.length);
    console.log($scope.tableHeight);
    $scope.gridApi.grid.handleWindowResize();
    $scope.gridApi.core.refresh();
  }, 200);


}]);
.grid {
  width: 600px;
}
<!doctype html>
<html ng-app="app">

<head>
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular-touch.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular-animate.js"></script>
  <script src="http://ui-grid.info/docs/grunt-scripts/csv.js"></script>
  <script src="http://ui-grid.info/docs/grunt-scripts/pdfmake.js"></script>
  <script src="http://ui-grid.info/docs/grunt-scripts/vfs_fonts.js"></script>
  <script src="http://ui-grid.info/release/ui-grid.js"></script>
  <link rel="stylesheet" href="http://ui-grid.info/release/ui-grid.css" type="text/css">
  <link rel="stylesheet" href="main.css" type="text/css">
</head>

<body>

  <div ng-controller="MainCtrl">
    <div ui-grid="gridOptions" ui-grid-pagination id="grid" style="{{tableHeight}}"></div>
    <div>
      <p>Current Page: {{ currentPage }}</p>
      <p>Total Page: {{ totalPage }}</p>
      <p>Page Size: {{ pageSize }}</p>
      <p>Table Height: {{tableHeight}}</p>
    </div>
  </div>


  <script src="app.js"></script>
</body>

</html>

Also see Plunker: http://plnkr.co/edit/np6y6rgN1ThnT0ZqyJeo?p=preview

Upvotes: 1

Purnima Nagpal
Purnima Nagpal

Reputation: 1

In the method where you are trying to store the data for each row within each grid, add a code to calculate the length of the grid in a separate array and push that calculated length to different array. Make sure the index of the grid and index of the array should be same, so that we can access it from the UI together. My approach was as follows:

                    //Stores the calculated height of each grid.
                    $scope.gridHeights = [];


                   //Returns the height of the grid based on the 'id' passed from the UI side.
                   //Returns the calculated height appended with 'px' to the HTML/UI
                    $scope.getHeight = function(id){
                        if($scope.gridHeights[id]) {
                            return {
                                'height': $scope.gridHeights[id] + 'px'
                            };
                        }else{
                            return {
                                'height': '300px'
                            };
                        }
                    };


                    for (var idx = 0; idx < $scope.auditData.length; idx++) {

                        //gets the rows for which audit trail/s has to be displayed based on single or multi order.
                        $scope.gridData[idx] = $scope.auditData[idx].omorderAuditTrailItems;

                        //Calculates and pushes the height for each grid in Audit Trail tab.
                        $scope.gridHeights.push(($scope.auditData[idx].omorderAuditTrailItems.length + 2)*30);


        //IN HTML, set the height of grid as :
        <div id='orderAuditTrailList'>
            <div class="row fits-auditTrail" ng-style="getHeight(id)">
                <div class="fits-ng-grid" ng-if="auditTrail.omorderAuditTrailItems.length>0" ng-grid="gridOrderAuditTrailList[id]" ng-style="getHeight(id)"></div>
            </div>
    </div>

Upvotes: 0

David Villacis C.
David Villacis C.

Reputation: 101

I find using this piece of code on the stylesheet solved my problem. I disabled the plugin but it works either way.

 .ngViewport.ng-scope{
    height: auto !important;
    overflow-y: hidden;
}

.ngTopPanel.ng-scope, .ngHeaderContainer{
    width: auto !important;
}
.ngGrid{
    background-color: transparent!important;
}

I hope it helps someone!

Upvotes: 0

Fan super
Fan super

Reputation: 1

you can add auto style something like this:

ng-style="{ 'height': myData.length*34 }",and myData is

Upvotes: 0

mrmbr007
mrmbr007

Reputation: 122

If you don't want to add any plugins I've implemented an easy solution to dynamically change the table's height strictly based on the visible rows. I am using Ui-Grid-Unstable v3.0. No need to touch CSS.

My HTML looks like:

<div id="grid1" ui-grid="gridOptions" ui-grid-grouping ui-grid-exporter class="grid"></div>

In your controller add:

$scope.$watch('gridApi.core.getVisibleRows().length', function() {
    if ($scope.gridApi) {
        $scope.gridApi.core.refresh();
        var row_height = 30;
        var header_height = 31;
        var height = row_height * $scope.gridApi.core.getVisibleRows().length + header_height;
        $('.grid').height(height);
        $scope.gridApi.grid.handleWindowResize();
    }
});

And to turn off scrolling add the following line where gridOptions is initialized:

enableVerticalScrollbar : uiGridConstants.scrollbars.NEVER,

Make sure uiGridConstants is passed into your controller:

angular.module('app').controller('mainController', function($scope, uiGridConstants) { ... 

Hope this helps!

Upvotes: 7

user3843934
user3843934

Reputation:

$(".gridStyle").css("height","");

remove your height property in your gridstyle class then automatic dynamic height set on your ng-grid..

Upvotes: 0

Alex Choroshin
Alex Choroshin

Reputation: 6187

You can try using the ng-grid Flexible Height Plugin, all you need to do is add this plugin to the plugins property in grid options and he'll take care of the rest .

Example:

$scope.gridOptions = {
    data: 'myData',
    enablePaging: true,
    showFooter: true,
    totalServerItems: 'totalServerItems',
    pagingOptions: $scope.pagingOptions,
    filterOptions: $scope.filterOptions,
    plugins: [new ngGridFlexibleHeightPlugin()]
};

Live example: http://plnkr.co/edit/zNHhsEVqmpQmFWrJV1KQ?p=preview

Upvotes: 33

Related Questions