KendoGrid/Angular: cannot create grid columns/data

2019-07-04 16:33发布

问题:

In this plunk I have an empty grid (without columns). When I click on "Build Grid" I need to add columns (taken from an array) and also add a row to the table.

The problem is that the columns are not added to the grid, any ideas? If I try to refresh the grid, I get an undefined error.

HTML:

<button ng-click="buildGrid()">Build Grid</button>
<div kendo-grid="grid" k-options="gridOptions" k-data-source="ds"></div>

Javascript:

var app = angular.module("app", [ "kendo.directives" ]);

function MyCtrl($scope) {

    $scope.ds = []

    $scope.colsList =  [{ name: "col1" },
                        { name: "col2" },
                        { name: "col3" },
                        { name: "col4" }];


  var gridCols = [];

    $scope.gridOptions = {
            columns: gridCols
  };


$scope.buildGrid = function() {

        $scope.data = {};

        for (var x=0;x<$scope.colsList.length;x++) {
            var col = {};
            col.field = $scope.colsList[x].name;
            col.title = $scope.colsList[x].name;
            $scope.data[col.field] = "" + (1111 * (x+1));
            gridCols.push(col);
        }

        // add one row to the table
        $scope.ds.push($scope.data);
        //$scope.grid.refresh();

    };  
}

回答1:

You need to use k-rebind so that the grid reinitializes (you can't set the columns dynamically on an existing grid):

<div kendo-grid="grid" 
     k-options="gridOptions" 
     k-data-source="ds" 
     k-rebind="gridOptions"></div>

(demo)