Kendo Grid: Getting widget instance in Angular

2019-05-01 16:08发布

I was trying to get an instance of the Kendo grid within my Angular Controller, so I can try and hook up to some events (and call methods) I know this is probably not best practice (and should probably use a custom directive), but according to the documentation, we should be able to use...

<div ng-app="app" ng-controller="MyCtrl">
<input kendo-datepicker="datePicker" k-on-change="onChange()">
</div>
<script>
 angular.module("app", [ "kendo.directives" ]).controller("MyCtrl",
   function($scope) {
 $scope.onChange = function() {
 alert($scope.datePicker.value());
};

});

So, I was trying to do the same with the grid. I have the following markup...

<div ng-controller="Grid">
  <div kendo-grid='grid' k-options="vm.gridOptions"></div>  
</div>

and then in the controller js file..

  angular
    .module("mygrid")
    .controller("Grid", ['$scope', Grid]);

    function Grid($scope) {             
      var gridInstance = $scope.grid;
      ...

as can be seen here

However, gridInstance is always undefined. Does anyone know if I shoud be able to do this with the grid, and if so why the above always returns undefined?

Thanks in advance for any help

Peter

1条回答
我想做一个坏孩纸
2楼-- · 2019-05-01 17:01

Two issues:

  1. If you use the "controller as" syntax, you need to prefix things you want to access (in your case, you need kendo-grid="vm.grid" instead of kendo-grid="grid"
  2. When your controller is instantiated, the Kendo UI widget doesn't exist yet (similar question here), so you need to wait on it using a global Kendo UI event

So your Html becomes:

<div data-ng-app="app">
    <div data-ng-controller="Grid as vm">
        <div kendo-grid="vm.grid" k-options="vm.options"></div>
        <div>{{vm.msg}}</div>
    </div>
</div>

Your app:

(function () {
    angular.module("app", ["kendo.directives"])
        .controller("Grid", ["$scope", Grid]);

    function Grid($scope) {
        var vm = this;

        var gridData = [{
            col1: 'data1',
            col2: 'data2'
        }, {
            col1: 'data1',
            col2: 'data2'
        }];

        vm.options = {
            dataSource: gridData,
            editable: true
        };

        $scope.$on("kendoRendered", function (event) {
            var gridInstance = vm.grid;
            console.log(vm);
            vm.msg = gridInstance === undefined ? "undefined" : "defined";
        });
    }
})();

(updated demo)

查看更多
登录 后发表回答