2

Here is a summary of the problem: I set up a column sortChange() listener, which responds to sort changes by firing off a query to fetch newly sorted data. I save the grid state before the fetch, and restore the grid state after the fetch. The problem is that the restore gridState mechanism triggers the original sort listener, causing the whole process to start over again, and again, and again.

scope.sitesGrid.onRegisterApi = function(gridApi) {
  scope.gridApi = gridApi;

  scope.gridApi.core.on.sortChanged(scope, function () {
    // load new sites on a sort change
    scope.initialize();
  });
};

scope.initialize = function() {
  // save current grid state
  scope.gridApi && (scope.gridState = scope.gridApi.saveState.save());

  fetchSites().then(function (sites) {
    scope.sitesGrid.data = sites
    // restore current grid state, but inadvertently retrigger the 'sortChanged' listener
    scope.gridApi.saveState.restore(scope,scope.gridState);
  })
};

I was thinking that I could set up a click listener on each column header, instead of using a sortChange listener, however this solution seems ugly and requires going into every header cell template and making changes.

efreezy
  • 253
  • 1
  • 3
  • 12

2 Answers2

1

How about some kind of scope variable to track the loading of data?

scope.gridApi.core.on.sortChanged(scope, function () {
    if (!scope.isLoading) {
        scope.initialize();
    }
});

and

fetchSites().then(function (sites) {
    scope.isLoading = true;
    scope.sitesGrid.data = sites;
    scope.gridApi.saveState.restore(scope,scope.gridState);
    scope.isLoading = false;
})

You might need to add some timeout() calls in places if there are timing issues with this. Creating a Plunker to demonstrate this would help in that case.

S. Baggy
  • 950
  • 10
  • 21
0

I think i find solution. I created restore function in my directive (u can use it where you want). I just block executing next iteration until action is finished.

function restoreState() {
    if ($scope.gridState.columns !== undefined && !isRestoring) {  //check is any state exists and is restored
        isRestoring = true;  //set flag
             $scope.gridApi.saveState.restore($scope, $scope.gridState)
                  .then(function () {
                       isRestoring = false;  //after execute release flag
                   });
    }

}

function saveState() {
    if (!isRestoring) {
        $scope.gridState = $scope.gridApi.saveState.save();
    }
}
Sławek S
  • 1
  • 2