2016-09-19 58 views
2

下面是問題的總結:我設置了一個列sortChange()偵聽器,它響應排序更改,通過觸發查詢來獲取新排序的數據。我在提取之前保存網格狀態,並在提取後恢復網格狀態。問題是,恢復gridState機制會觸發原始排序偵聽器,導致整個過程重新開始,並且再次重新開始。UI-grid saveState服務循環邏輯

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監聽器,但這個解決方法看起來醜陋和需要去到每一個標題單元格模板並進行修改。

回答

1

如何跟蹤某種範圍變量來跟蹤數據的加載?

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

您可能需要的地方增加一些timeout()電話,如果有這個時間的問題。創建一個Plunker來證明這一點將有助於這種情況。