5

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

peterc
  • 6,921
  • 9
  • 65
  • 131

1 Answers1

5

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)

Community
  • 1
  • 1
Lars Höppner
  • 18,252
  • 2
  • 45
  • 73
  • Thanks you once again Lars! Your knowledge of this grid and/with Angular is impressive. My last piece of the puzzle would be to get this in a directive. I thought it would be the same way but haven't quite got it. I thought since this is an extention I should use another post (http://stackoverflow.com/questions/28470493/kendo-grid-getting-an-instance-in-a-angular-directive). Thanks again for your help here – peterc Feb 12 '15 at 06:10