2014-02-28 40 views
1

我正在使用ngGrid顯示源自數據庫的數據。使用ngGrid文檔中描述的方法,我可以在網格中將更改寫回數據庫。但是,如果db響應寫入錯誤,我一直無法找到恢復到原始值的方法。如果數據庫寫入失敗,則恢復爲ngGrid中的原始單元格值

下面是我使用的電池模板和更新功能:

var cellEditableTemplate = "<input ng-class=\"'colt' + col.index\" ng-input=\"COL_FIELD\" ng-model=\"COL_FIELD\" ng-blur=\"updateEntity(col, row, COL_FIELD)\" />"; 

$scope.updateEntity = function(column, row, cellValue){ 
    console.log(row.entity); 
    console.log(column.field); 
    console.log('Cell Value prior: ' + row.entity[column.field]); 
    console.log('Cell Value after: ' + cellValue); 

    //Trying to cache original value, i know this is wrong. 
    var fail = row.entity[column.field]; 

    //row.entity[column.field] = cellValue; 

    var map = {}; 
    map[column.field] = cellValue; 

    //Code to prevent multiple ngBlur events 
    //http://technpol.wordpress.com/2013/12/06/editable-nggrid-with-both-dropdowns-and-selects/ 
    if(!$scope.save) { 
     $scope.save = {promise: null, pending: false, data: null}; 
    } 

    $scope.save.data = map; 
    if(!$scope.save.pending){ 
     $scope.save.pending = true; 
     $scope.save.promise = $timeout(function(){ 
     //DB Write Function 
     $scope.update(row.entity.id, $scope.save.data).then(
     function (result){ 
      //DB Write Success 
      //Ensure new value is written to scope 
      $scope.log("Table Updated", result); 
      row.entity[column.field] = cellValue; 
     }, function (error){ 
      //DB Write Failure 
      //Need to revert to original value 
      $scope.log("Error updating value", error); 
      row.entity[column.field] = fail; //I know this doesn't work! 
     }); 
     $scope.save.pending = false; 
     }, 500); 
    } 
    }; 

這段代碼的審查清楚地表明,設置NG-模型在模板中COL_FIELD意味着每次更新單元格的值立即應用於示波器。所以我需要的是在任何編輯發生之前緩存原始值的方法。

對此提出建議?

回答

2

在你editableCellTemplate,使用ngFocus指令調用緩存行的函數:

ng-focus="cacheRow(row.entity)" 

其中cacheRow()看起來是這樣的:

$scope.cacheRow = function(startValue) { 
    $scope.rowHolder = {}; 
    angular.copy(startValue, $scope.rowHolder); 
}; 

然後在updateEntity()您可以比較新值和舊值以確定它們是否相同(以避免不必要地更新),並且如果數據庫更新失敗,也可以使用緩存的行來還原:

if (!angular.equals($scope.rowHolder, row.entity)) { 
    //update here 
    ... 
    //on DB write fail, reset to $scope.rowHolder 
} 
0

有更簡單的方法。 DB-寫後gridApi.edit.on.afterCellEdit失敗,您可以恢復原來的值:

 $scope.gridOptions.onRegisterApi = function(gridApi){ 
      $scope.gridApi = gridApi; 

      gridApi.edit.on.afterCellEdit($scope,function(rowEntity, colDef, newValue, oldValue) { 
       if (colDef.name === 'comment' && newValue !== oldValue) { 
        var entity = new Entity(); 
        entity.id = rowEntity.id; 
        entity.comment = newValue; 
        $scope.updateEntity(entity) 
         .then(function (value) { 
         }, 
          function(error) { 
           rowEntity.comment = oldValue; 
           Messages.on_http_error(error); 
          }); 
       } 
       $scope.$apply(); 
      }); 

};

$ scope.updateEntity(entity)是你應該返回promise的函數。

相關問題