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

时间:2015-08-11 08:53:45

标签: angularjs angular-ui-grid

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

$ rootScope.columns = [{                 字段:' id',                 displayName:' 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();
                    })

1 个答案:

答案 0 :(得分:0)

我不确定你的问题究竟是什么,但重建ui-grid是可能的。所需要的只是更改数据和更新列定义。以下示例说明了此行为。

我的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找到一个工作示例。