Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular ui-grid/ng-grid filterChanged firing too frequently

I'm trying to implement a grid in angular, using server-side sorting, server-side pagination and server-side filtering. Using ui-grid (unstable), I added ui.grid.paging and got everything up and running. Very nice, kudos to the developers.

However.... $scope.gridApi.core.on.filterChanged is firing for every key pressed, so when I search for "Patrick" in the givenname column, seven events are fired and seven get-requests hit my server. Even worse, since it is a large set I'm filtering, this operation is pretty expensive and the results my even overtake each other, like the most specific filter getting the fastest result, triggering success before a less specific result is processed.

I'd like to slow it down, like "fire after entry has stopped". I'm pretty much new to javascript and REST, this is my first real-world-project. I would really appreciate any ideas how to handle this issue. It feels like a common scenario, so there might be some standard solutions or best practices I'm missing.

Yours, Patrick.

like image 917
user3700169 Avatar asked Dec 04 '14 18:12

user3700169


1 Answers

If you wanna go "all angular" I would suggest to use a $timeout inside the on.filterChanged event handler:

if (angular.isDefined($scope.filterTimeout)) {
    $timeout.cancel($scope.filterTimeout);
}
$scope.filterTimeout = $timeout(function () {
    getPage();
}, 500);

where 500 is the time (in milliseconds) you would like to wait between each on.filterChanged event before going to the server and getPage() is the function that actually goes to the server and retrieves the data.

Don't forget to cancel your $timeout on the controller's 'destroy' event:

$scope.$on("$destroy", function (event) {
    if (angular.isDefined($scope.filterTimeout)) {
        $timeout.cancel($scope.filterTimeout);
    }
});
like image 194
Santiago Robledo Avatar answered Nov 23 '22 17:11

Santiago Robledo