How can I refresh a grid data source using angular Kendo UI

前端 未结 3 1862
暖寄归人
暖寄归人 2021-02-05 08:20

I am combining Telerik Kendo grid with Angular using the Angular Kendo UI project.

I have the following markup:

3条回答
  •  -上瘾入骨i
    2021-02-05 08:54

    So I recently struggled with this as well.

    The key, it seams is to call the .read() function on the Datasource object. Unfortunately, i've only found out how to do this from a jQuery style call like this:

    angular.element('#theGrid').data("kendo-grid").dataSource.read(); 
    

    Now of all that, the id selector "#theGrid" will depend on your implementation and what your containing div is Id'd as. Confusingly, the .data("kendo-grid") bit is hard coded in the Angular directive and will be the same regardless of your implementation.

    I know you're not supposed to do Dom Manipulation in Angular, but needing to lazy-load a complex Kendo grid necessitated a bit of angular magic/hacking. I created a "refresh grid" function that enables a promise-based flow control over a dom-element so that I can refresh the grid after the grid has instantiated itself. Here's an example implementation of that:

    #this is in a service called KendoGridService, so understand the context.
    stop: undefined,
        refreshGrid: function() {
        // don't queue another refresh of the grid.
        if (angular.isDefined(KendoGridService.stop)) return;
    
        var element = angular.element("#kgrid");
            KendoGridService.stop = $interval(function() {
                if(angular.element("#kgrid").data("kendo-grid")){
                KendoGridService.stopRefreshLoop(element);
                }
            }, 100, 10);
        },
        stopRefreshLoop: function(element) {
            if (angular.isDefined(KendoGridService.stop)) {
            angular.element("#kgrid").data("kendo-grid").dataSource.read();
            $interval.cancel(KendoGridService.stop);
            KendoGridService.stop = undefined;
            }
        },
    

    With this in place, you can now do the basic load of your grid data, then refresh it after your (presumably promised based) updates complete by calling (in this case):

    KendoGridService.refreshGrid();
    

    that method uses the $interval service built into Angular to run itself every 100ms, for a maximum of 10 iterations. IF during any of those iterations, the dom element is found, the stopRefreshLoop method is called.

    As far as hacks go, i think it's on the "more elegant" side of hacks.

提交回复
热议问题