UI-grid saveState服务循环逻辑

时间:2016-09-19 22:54:43

标签: angularjs angular-ui-grid ui-grid

以下是问题的摘要:我设置了一个列sortChange()侦听器,它通过触发查询以获取新排序的数据来响应排序更改。我在获取之前保存网格状态,并在获取之后恢复网格状态。问题是恢复gridState机制触发了原始的排序监听器,导致整个过程重新开始,一次又一次。

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);
  })
};

我想我可以在每个列标题上设置一个点击监听器,而不是使用sortChange监听器,但是这个解决方案看起来很难看,需要进入每个标题单元格模板并进行更改。

2 个答案:

答案 0 :(得分:1)

某种范围变量如何跟踪数据加载?

git add [filePath]

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

如果存在时间问题,您可能需要在地方添加一些fetchSites().then(function (sites) { scope.isLoading = true; scope.sitesGrid.data = sites; scope.gridApi.saveState.restore(scope,scope.gridState); scope.isLoading = false; }) 次来电。在这种情况下,创建一个Plunker来证明这一点会有所帮助。

答案 1 :(得分:0)

我想我找到了解决方案。我在指令中创建了恢复功能(您可以在需要的地方使用它)。我只是阻止执行下一次迭代,直到动作完成为止。

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();
    }
}