web-dev-qa-db-fra.com

ng-grid Auto/Dynamic Height

Comment obtenir que ng-grid redimensionne automatiquement sa hauteur en fonction de la taille de la page? La documentation sur le site de ng-grid utilise une hauteur fixe. La meilleure solution que j'ai vue vient de ce link :

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

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

Cela ne fonctionne pas avec la pagination côté serveur. J'ai copié l'exemple de pagination côté serveur depuis le site de ng-grid et appliqué les css ci-dessus, mais comme vous pouvez le constater, seules les 6 premières lignes sont affichées: http://plnkr.co/edit/d9t5JvebRjUxZoHNqD7K? p = aperçu

Et {height: 100%} ne fonctionne pas ... 

19
CalebG

Vous pouvez essayer d’utiliser le ng-grid Flexible Height Plugin , tout ce que vous avez à faire est d’ajouter ce plugin à la propriété plugins dans les options de la grille et il se chargera du reste.

Exemple:

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

Exemple en direct: http://plnkr.co/edit/zNHhsEVqmpQmFWrJVKK?p=preview

31
Alex Choroshin

Si vous ne souhaitez pas ajouter de plug-in, j'ai mis en place une solution simple pour modifier dynamiquement la hauteur de la table en fonction des lignes visibles. J'utilise Ui-Grid-Unstable v3.0. Pas besoin de toucher CSS.

Mon HTML ressemble à:

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

Dans votre contrôleur, ajoutez:

$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();
    }
});

Et pour désactiver le défilement, ajoutez la ligne suivante où gridOptions est initialisé:

enableVerticalScrollbar : uiGridConstants.scrollbars.NEVER,

Assurez-vous que uiGridConstants est passé dans votre contrôleur:

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

J'espère que cela t'aides!

5
mrmbr007

Je pense avoir parfaitement résolu ce problème après 48 heures,

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>

Voir aussi Plunker: http://plnkr.co/edit/np6y6rgN1ThnT0ZqyJeo?p=preview

1
Belter

Je trouve en utilisant ce morceau de code sur la feuille de style résolu mon problème. J'ai désactivé le plugin mais cela fonctionne dans les deux cas.

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

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

J'espère que ça aide quelqu'un!

0

vous pouvez ajouter un style automatique à quelque chose comme ceci: 

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

0
Fan super

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

supprimez votre propriété height dans votre classe gridstyle, puis définissez automatiquement la hauteur dynamique sur votre ng-grid.

0
user3843934

Dans la méthode dans laquelle vous essayez de stocker les données pour chaque ligne de chaque grille, ajoutez un code pour calculer la longueur de la grille dans un tableau séparé et transmettez cette longueur calculée à un autre tableau. Assurez-vous que les index de la grille et du tableau doivent être identiques, afin que nous puissions y accéder simultanément à partir de l'interface utilisateur. Mon approche était la suivante: 

                    //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>
0
Purnima Nagpal