Угловая сетка пользовательского интерфейса, изменение поведения экспорта всех данных в формате csv

У меня есть ugrid, который содержит большое количество определений столбцов, которые изначально не заполнены данными, потому что набор данных будет слишком большим. Вместо этого я получаю запрошенные данные столбца при изменении видимости столбца.

Это вызывает проблему со встроенным экспортером csv. Когда кто-то выбирает «Экспортировать все данные в формате csv», он получает множество пустых столбцов.

Что бы я хотел сделать, это изменить поведение по умолчанию встроенных элементов меню csv для использования uiGridExporterConstants.VISIBLE.

Я собирался перевернуть свои собственные пункты меню так:

  $scope.gridOptions.exporterMenuCsv = false; //Rolling our own menu items to exclude invisible columns
  $scope.gridOptions.gridMenuCustomItems = [
      {
          title: 'Export All to CSV',
          action: function ($event) {
              var myElement = angular.element(document.querySelectorAll(".custom-csv-link-location"));
              $scope.gridApi.exporter.csvExport( uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE, myElement );
          }
      },{
          title: 'Export Selected to CSV',
          action: function ($event) {
              var myElement = angular.element(document.querySelectorAll(".custom-csv-link-location"));
              $scope.gridApi.exporter.csvExport( uiGridExporterConstants.SELECTED, uiGridExporterConstants.VISIBLE, myElement );
          }
      },{
          title: 'Export Visible to CSV',
          action: function ($event) {
              var myElement = angular.element(document.querySelectorAll(".custom-csv-link-location"));
              $scope.gridApi.exporter.csvExport( uiGridExporterConstants.VISIBLE, uiGridExporterConstants.VISIBLE, myElement );
          }
      }
  ];

Но появляется только первый элемент. Возможно, мне нужно использовать addToGridMenu, но я не уверен. В идеале я хотел бы оставить элементы по умолчанию на месте, но просто «экспортировать все данные в формате csv» экспортировать только видимые столбцы.


person anthozep    schedule 09.12.2015    source источник


Ответы (1)


В итоге мне пришлось использовать gridApi.core.addToGridMenu так:

    $scope.gridOptions = {
            exporterCsvLinkElement: angular.element(document.querySelectorAll('.custom-csv-link-location')),
            onRegisterApi: function(gridApi){
                $scope.gridApi = gridApi;

                $interval(function () {
                    gridApi.core.addToGridMenu(gridApi.grid, [{
                        title: 'Export All to CSV',
                        order: 1,
                        action: function ($event) {
                            var myElement = angular.element(document.querySelectorAll(".custom-csv-link-location"));
                            $scope.gridApi.exporter.csvExport(uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE, myElement);
                        }
                    }]);
                    gridApi.core.addToGridMenu(gridApi.grid, [{
                        title: 'Export Visible to CSV',
                        order: 2,
                        action: function ($event) {
                            var myElement = angular.element(document.querySelectorAll(".custom-csv-link-location"));
                            $scope.gridApi.exporter.csvExport(uiGridExporterConstants.VISIBLE, uiGridExporterConstants.VISIBLE, myElement);
                        }
                    }]);
                }, 0, 1);

                $scope.gridApi.selection.on.rowSelectionChanged($scope, function () { //for single row selection
                    if (gridApi.grid.selection.selectedCount > 0 && !selectionMenuAdded) { //only add menu item if something is selected and if the menu item doesn't already exist
                        selectionMenuAdded = true;
                        gridApi.core.addToGridMenu(gridApi.grid, [{
                            title: 'Export Selected to CSV',
                            order: 3,
                            id: 'uiSel',
                            action: function ($event) {
                                if (gridApi.grid.selection.selectedCount > 0) {
                                    var uiExporter = uiGridExporterService;
                                    var grid = $scope.gridApi.grid;
                                    uiExporter.loadAllDataIfNeeded(grid, uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE).then(function () {
                                        var exportColumnHeaders = uiExporter.getColumnHeaders(grid, uiGridExporterConstants.VISIBLE);
                                        var selectionData = [];
                                        gridApi.selection.getSelectedRows().forEach(function (entry) {
                                            var innerData = [];
                                            for (var e in entry) { //create the inner data object array
                                                if (e !== '$$hashKey') {
                                                    var selectObj = { value: entry[e] };
                                                    innerData.push(selectObj);
                                                }
                                            }
                                            selectionData.push(innerData); //push the inner object value array to the larger array as required by formatAsCsv
                                        });
                                        var csvContent = uiExporter.formatAsCsv(exportColumnHeaders, selectionData, grid.options.exporterCsvColumnSeparator);
                                        uiExporter.downloadFile($scope.gridOptions.exporterCsvFilename, csvContent, grid.options.exporterOlderExcelCompatibility);
                                    });
                                }
                            }
                        }]);
                    } else if (gridApi.grid.selection.selectedCount === 0 && selectionMenuAdded) {
                        selectionMenuAdded = false;
                        gridApi.core.removeFromGridMenu(gridApi.grid, 'uiSel');
                    }
                });

                $scope.gridApi.selection.on.rowSelectionChangedBatch($scope, function () {
                    if (gridApi.grid.selection.selectedCount > 0 && !selectionMenuAdded) {
                        selectionMenuAdded = true;
                        gridApi.core.addToGridMenu(gridApi.grid, [{
                            title: 'Export Selected to CSV',
                            order: 3,
                            id: 'uiSel',
                            action: function ($event) {
                                if (gridApi.grid.selection.selectedCount > 0) {
                                    var uiExporter = uiGridExporterService;
                                    var grid = $scope.gridApi.grid;
                                    uiExporter.loadAllDataIfNeeded(grid, uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE).then(function () {
                                        var exportColumnHeaders = uiExporter.getColumnHeaders(grid, uiGridExporterConstants.VISIBLE);
                                        var selectionData = [];
                                        gridApi.selection.getSelectedRows().forEach(function (entry) {
                                            var innerData = [];
                                            for (var e in entry) {
                                                if (e !== '$$hashKey') {
                                                    var selectObj = { value: entry[e] };
                                                    innerData.push(selectObj);
                                                }
                                            }
                                            selectionData.push(innerData);
                                        });
                                        var csvContent = uiExporter.formatAsCsv(exportColumnHeaders, selectionData, grid.options.exporterCsvColumnSeparator);
                                        uiExporter.downloadFile($scope.gridOptions.exporterCsvFilename, csvContent, grid.options.exporterOlderExcelCompatibility);
                                    });
                                }
                            }
                        }]);
                    } else if (gridApi.grid.selection.selectedCount === 0 && selectionMenuAdded) {
                        selectionMenuAdded = false;
                        gridApi.core.removeFromGridMenu(gridApi.grid, 'uiSel');
                    }
                });
          }
    }

Обязательно внедрите uiGridExporterConstants и uiGridExporterService.

person anthozep    schedule 05.01.2016