2016年1月18日 星期一

ag-grid 使用範例

//宣告
agGrid.initialiseAgGridWithAngular1(angular);
angular.module('module1', ['agGrid']).controller('ctrl1', function ($scope, $http, $filter) {

//初始設定
$scope.gridOptions = {
            enableFilter: true, floatingFilter: true, suppressMenu: true, // 加入即時篩選方塊
            suppressMovableColumns: true,
                angularCompileRows: true,
                rowSelection: 'single',
                enableColResize: true,
                enableSorting: true,
 onCellFocused: function (event) {
                if ($scope.gridOptions.api.getModel().rowsToDisplay[event.rowIndex]) $scope.gridOptions.api.getModel().rowsToDisplay[event.rowIndex].setSelected(true);
            }, // 使用鍵盤方向鍵自動選取列
defaultColDef: {
                    suppressMenu: true, floatingFilterComponentParams: { suppressFilterButton: true } // 使用即時篩選方塊時隱藏不要顯示的物件
                },
            columnDefs: [
{
          headerName: '日期', width: 100, cellStyle: { 'text-align': 'center'}, cellRenderer: function (params) {
              return $filter('date')(new Date(params.value), 'yyyy/MM/dd');
          },filter: 'agTextColumnFilter', filterParams: {
              textCustomComparator: function (filter, value, filterText) {
                  var datestring = $filter('date')(new Date(value), 'yyyyMMdd');
                  return datestring.indexOf(filterText) >= 0;
              }, // 日期篩選要透過客製化達成
          }
      },

※ 避免在 cellRenderer 中執行非 return 指令,避免畫面無法自動更新而必須透過 redrawrows 引發其他問題

//寫入資料
$scope.getlist = function () {
            $http.post('@Url.Action("查詢")', { fromdate: $scope.fromdate, todate: $scope.todate })
                    .then(function (result) {
                        $scope.gridOptions.api.setRowData(result.data);
                    }).catch(function (data) {
                        if (data.status != '') alert(data.statusText);
                        else alert('發生錯誤,請重新整理頁面後再試一次');
                        console.log(data.data);
                    });
        };

//html
<script type="text/javascript" src="~/scripts/ag-grid.min.js"></script>
<link href="~/Content/ag-grid.min.css" rel="stylesheet" type="text/css" />
<link href="~/Content/theme-fresh.min.css" rel="stylesheet" type="text/css" />
<div id="divlist" ag-grid="gridOptions" class="ag-fresh" ng-style="getTableHeight()"></div>

//css
讓 form-control 佔滿全部寬度
.ag-cell > span {
        width: 100%;
    }

避免cell使用 div 內含<br>時造成空隙太大
.ag-cell {
    line-height: unset !important;
}

垂直置中 (有設定高度會需要)
.ag-cell {
display: flex !important;align-items: center;
}

.ag-header-cell-label {
       width: 100% !important; // 避免欄位名稱要設定很寬否則顯示不完全而出現...
    justify-content: center; // 置中
    }

欄位左右間距調整
.ag-header-cell, .ag-header-group-cell, .ag-cell {
        padding-left: 5px;
        padding-right: 5px;
    }

不要強制設定字型
.ag-theme-balham,.ag-header {
    font-size: unset !important;
}

點選欄位不要出現外框
.ag-cell-focus {
    border: unset;
}

若用到 display: flex,且未使用cellRenderer,則水平靠右對齊方式改為
cellStyle: { 'justify-content': 'flex-end' }


計算筆數
$scope.gridOptions.api.getDisplayedRowCount(); // 篩選後筆數
$scope.gridOptions.api.getModel().rootNode.allLeafChildren.length; // 完整筆數

取得nodes (不要直接抓 rowData)
$scope.gridOptions.api.getModel().rowsToDisplay
Enumerable.From($scope.gridOptions.api.getModel().rowsToDisplay).Select('$.data').ToArray(); // 取data

若 cellRenderer 使用 {{}} 顯示內容,有些情況會造成沒有確實轉換,此時可以透過以下方式解決
$timeout(function () {
                if (!$scope.$$phase) $scope.$apply();
            }, 100);


載入資料後某欄位沒有任何資料則不顯示避免無用欄位太多
Enumerable.From($scope.gridOptions.columnDefs).ForEach(function (col) {
            $scope.gridOptions.columnApi.setColumnVisible(col.field, Enumerable.From($scope.gridOptions.rowData).Any('$.'+col.field+''));
                      });


排序依照中文筆畫
{ field: '名稱', headerName: '名稱', comparator: textComparator },
function textComparator(a, b, d1, d2, isInverted) {
                return a.localeCompare(b, "zh-Hant");
            }


避免凍結欄位時出現捲軸
.ag-pinned-left-cols-viewport {
    overflow-y: hidden !important;
}

沒有留言:

自訂權限驗證機制

// 使用 filter [Route("api/[controller]")] [ApiController] [Authorize] [TypeFilter(typeof(CustomAsyncAuthorizationFilter))] public c...