如何使用ag-grid动态显示列

时间:2016-01-02 06:39:00

标签: angularjs ag-grid

我是angularjs技术的新手。我正在使用ag-grid并希望动态显示列

我的json数据是:

[{Date:'12-12-2015',Name:'ammu',mark:20},{Date:'12-12-2015',Name:'appu',mark:24},{Date:'12-12-2015',Name:'anu',mark:27},{Date:'13-12-2016',Name:'ammu',mark:23},{Date:'13-12-2015',Name:'anu',mark:20}]

我的预期输出是 Expected Output

现有代码如下:

$scope.gridOptions = {
    columnDefs: [],
    enableFilter: true,
    rowData: [],
    rowSelection: 'multiple',
    rowDeselection: true
};
 $scope.customColumns = [];
Getdetails();
function Getdetails()
{
    masterdataFactory.Getdetails()
     .success(function (Student) {
        f (Student.length != 0) {
             for(var i=0;i<Student.length;i++) {
                 $scope.customColumns.push(
                     {
                         headerName: Student[i].Name,
                         field: "Mark",
                         headerClass: 'grid-halign-left'

                     }
                 );
             };
            $scope.gridOptions.columnDefs = $scope.customColumns;
            $scope.gridOptions.rowData = Student;
            $scope.gridOptions.api.setColumnDefs();
          }                 
     })
      .error(function (error) {
          $scope.status = 'Unable to load data: ' + error.message;
      });
}

现有产出如下 Existing Output

如何从现有输出中达到我的预期输出

7 个答案:

答案 0 :(得分:4)

首先安排json数据

[{Date:'12-12-2015',ammu:20,appu:24,anu:27},{Date:'13-12-2016' ammu:23,anu:20}]

为此我正在使用以下代码

             function generateChartData() {
             var chartData = [],
               categories = {};
             debugger;
             for ( var i = 0; i <Student.length; i++ ) {
                 var newdate = Student[ i ].Date;
                 var Name=Student[ i ].Name;
                 var Mark=Student[ i ].Mark;
                // add new data point
                 if ( categories[ newdate ] === undefined ) {
                     categories[ newdate ] = {
                         DATE: newdate
                     };
                     chartData.push( categories[ newdate ] );
                 }

                 // add value to existing data point

                 categories[ newdate ][ Name] = Mark;
             }

             return chartData;
         }

网格选项如下:

 $scope.gridOptions = {
             columnDefs: coldef(),
             enableFilter: true,
             rowData: [],
             rowSelection: 'multiple',
             rowDeselection: true,
             enableColResize: true,

             }
           };
        $scope.gridOptions.columnDefs = $scope.customColumns;
        $scope.gridOptions.rowData =generateChartData();
        $scope.gridOptions.rowData = generateChartData();
}

列定义是动态的,如下所示

  function coldef()
{
    for(var i=0;i<headers.length;i++) {
        debugger;
        $scope.customColumns.push(
                              {
                                  headerName: headers[i],
                                  field:headers[i],
                                  headerClass: 'grid-halign-left',
                                  width:180,
                                  filter: 'set',
                             });
        } }
此标头中的

是一个数组。此数组包含不同的学生姓名

 var headers=new Array();
 headers[0]="DATE";
 var Names= Student.map(function (item) { return item.Name}); 
 Names= Names.filter(function (v, i) { return Names.indexOf(v) == i; }); 
         for(var i=1;i<=Names.length;i++)
         {
             headers[i]=Names[i-1];
         }

答案 1 :(得分:2)

您似乎正在使用异步调用来获取数据,因此当调用超过时,网格已经初始化。

网格初始化后,您需要使用网格API(gridOptions.api ...)而不是girdOptions.columnsDef(请参阅http://www.ag-grid.com/angular-grid-api/index.php

答案 2 :(得分:2)

您的代码中存在一些错误:

第一:&#39; API&#39;字段在开始时不可用。它可能意味着两件事:

  1. 网格尚未加载(在http://www.ag-grid.com上的$timeout或就绪事件检查文档中打包电话。
  2. 您忘记了DOM元素中的ag-grid指令,因此网格根本不会初始化。
  3. 第二次:不要使用$scope.gridOptions.api.setColumnDefs();$scope.gridOptions.api.setColumnDefs(myNewColumnsDefs);

    第三次:如果网格已经初始化,请不要使用rowData使用api.setRowData(myDatas),可能最好在调用setColumnDefs后使用它,但我不知道#39;认为它会弄乱任何东西。

答案 3 :(得分:2)

// the api will not be available unless it is compiled with the **$timeout** or **setTimeout** because this javascript library does not fall in angular digest cycle
$timeout(function() {
  $scope.gridOptions.api.setColumnDefs(masterColumnDefs);
}, 0);

这将帮助您访问ag-grid的API。

希望这有帮助!

答案 4 :(得分:0)

我认为数据输入数据(学生)可能是罪魁祸首,因为括号似乎是奇怪的配对(复制数据,但格式化更容易阅读):

[
    {Date:'12-12-2015',Name:'ammu',mark:20},
    Date:'12-12-2015',Name:'appu',mark:24},
    Date:'12-12-2015',Name:'anu',mark:27},
    Date:'13-12-2016',Name:'ammu',mark:23},
    {Date:'13-12-2015',Name:'anu',mark:20}
]

第二行,第三行和第四行没有开头{

答案 5 :(得分:0)

    $scope.gridOptions ={
        enableSorting: true,
        enableFilter: true,
        suppressMovableColumns:true,
        enableColResize: true,
        columnDefs : [],
        rowHeight : 27,
        tooltipField : true,
        suppressLoadingOverlay : true,
        overlayLoadingTemplate: '<span class="ag-overlay-loading-center" style=background:lightgoldenrodyellow>Please wait while your rows are loading</span>',
        //getRowStyle : getRowStyleScheduled
    };       

    $scope.gridRefresh = function() { 
$scope.columnsHeaders =[];
        for (var i = 0, len = $scope.columnsHeaders.length; i < len; i++) {
            $scope.columnsHeaders[i].headerName = $scope.columnsHeaders[i].name;
            $scope.columnsHeaders[i].field = $scope.columnsHeaders[i].field;
            $scope.columnsHeaders[i].cellRenderer = function(params) {
                if(params.value != null) {
                    return '<span title="'+params.value+'">'+params.value+'</span>';
                }else {
                    return null;
                }
            }
         $scope.gridOptions.columnDefs.push($scope.columnsHeaders[i]);
        }
        $scope.gridOptions.api.setColumnDefs($scope.gridOptions.columnDefs);
        $scope.gridOptions.api.setRowData($scope.Rows);
        $scope.gridOptions.columnApi.autoSizeColumns($scope.gridOptions.columnDefs);
    }

答案 6 :(得分:0)

我正在用角度6寻找相同的东西。但是此页面出现在Google中。如果有人想从其他API导出列定义,我会在角度6中提供答案,

由于列是动态的,因此我使用大小列进行调整,以使其适合可用的网格宽度

ngOnInit() {
this.gridOptions = {
  onGridSizeChanged: () => {
    this.gridApi.sizeColumnsToFit();
  },
  onNewColumnsLoaded: () => {
    if (this.gridApi) {
      this.gridApi.sizeColumnsToFit();
    }
  },
  defaultColDef: {
    width: 150,
    minWidth: 100,
    maxWidth: 400
  }
};
this.getcolumnData();

}

getcolumnData() {
this.pageType =  this.route.snapshot.paramMap.get('type');
this.http.get(`${this.baseURL}/getStaticMetaData`).subscribe(res => {
  let columnDef = [];
  res.forEach(column => {
    columnDef = [...columnDef, {headerName: column.columnName, field: column.columnId}];
  });
  this.gridApi.setColumnDefs(columnDef);
});

}

onGridReady(params) {
this.gridApi = params.api;
this.http.get(`${this.baseURL}/getStaticData`).subscribe(data => {
  if (data.length < 20) {
    this.isSmallGrid = true;
  }
  this.gridApi.setRowData(data);
}, err => {
  // handle error
});

}

<ag-grid-angular style="width: 100%;" 
  [ngStyle]="{'height.px': isSmallGrid ? '325' : '725'}"
  class="ag-theme-balham"
  [gridOptions]="gridOptions"
  (gridReady)="onGridReady($event)"
  enableColResize enableSorting enableFilter
  >
  </ag-grid-angular>