如何根据 $http 响应在 angular ui 网格中动态添加列

How to add column dynamicaly in angular ui grid depending on $http response

我们想在 $http 响应数据的响应中在现有 uiGrid 中添加新列。

$rootScope.columns = [{ 字段:'id', 显示名称:'NSX Controller', 宽度:“25%”

        },{
            field: 'syslogServer',
            displayName: 'IP',
            width: "40%"
        },{
            field: 'port',
            displayName: 'Port',
            width: "10%"
        },{
            field: 'protocol',
            displayName: 'Protocol',
            width: "10%"
        }];
    $rootScope.gridOptionsController = {
        showSelectionCheckbox: true,
        enableRowSelection: true,
        enableSelectAll: true,
        multiSelect: true,
        columnDefs: $rootScope.columns
        }


        .success(function(response) {                       
                    $rootScope.gridOptionsController.data = response;
                         $rootScope.columns.push({field: 'status',displayName: 'status',width: "10%"});
                         $rootScope.gridApiCont.core.refresh();
                    })

我不确定您的问题到底是什么,但是重新ui填充ui-网格是可能的。 required 所要做的就是更改数据和更新列定义。以下示例说明了此行为。

我的 html 是不言自明的:

<body>
    <div ng-controller="MainCtrl as m">
      <button ng-click="m.show('items.json')">Items</button>
      <button ng-click="m.show('employees.json')">Employees</button>
      <div ui-grid="m.gridOptions" class="grid"></div>
    </div>
  </body>

处理数据检索和列定义更改的脚本:

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

  //a reference to this
  var self = this;

  //grid options.
  this.gridOptions = {
    enableSorting: true,
    columnDefs: self.columns
  };

  //changes the column definitions based on the property names of the object
  this.change = function(data) {
    var properties = Object.getOwnPropertyNames(data[0]);
    self.columns = [];
    properties.forEach(function(property) {
      self.columns.push({
        'field': property
      });
    });
    self.gridOptions.columnDefs = self.columns;
  };

  //retrieves the json file and sets the gridoption data
  this.show = function(file) {
    $http.get(file).success(function(data) {
        self.change(data);
        self.gridOptions.data = data;
      });
  };

  //initialize the first table
  this.show('items.json');

}]);

也可以在 this plunker 上找到工作示例。