2014-09-01 73 views
0

我正面臨在ng-grid中添加具有計算字段的新行的問題。在ng-grid中添加具有計算字段的新行

HTML代碼..

<div class="costsheetGrid" ng-controller="costsheetGridController"> 
     <p> 
      <a class="btn btn-lg btn-primary" ng-click="addAnotherRow()" href="javascript:void(0);">Add Another Row</a> 
     </p> 
     <div class="gridStyle" ng-grid="gridOptions"> 
     </div> 
    </div> 

JavaScript代碼..

$scope.gridData = [ 
      { 
       'Consumption': '100', 
       'ConversionQuantity': '3', 
      } 
     ]; 

angular.forEach($scope.gridData, function (row) { 
       row.getActualConsumption = function() { 
        return row.Consumption/row.ConversionQuantity; 
       }; 
      }); 

$scope.gridOptions = { 
      data: 'gridData', 
      enableCellSelection: true, 
      enableRowSelection: false, 
      enableCellEditOnFocus: true, 
      columnDefs: [ 

      { field: "Consumption", displayName: "Consumption", width: 100 }, 

      { field: "ConversionQuantity", displayName: "Conversion Quantity", width: 120 }, 
      { field: "getActualConsumption()", displayName: "Actual Consumption", width: 120, enableCellEdit: false } 
     ] 
     }; 

$scope.addAnotherRow = function() { 
      $scope.gridData.push({ 
       'Consumption': '', 
       'ConversionQuantity': '', 
      }); 
     }; 

此代碼工作完全當我在網格的第一行改變消費或ConversionQuantity,並計算出實際消費。當我點擊「添加另一個行」按鈕時,它會添加一個新行,但是當我在第二行插入消費量或ConversionQuantity時,則無法計算實際消耗量。

那麼,我該如何做到這一點?

回答

1

您只在初始數據上爲每行附加getActualConsumption函數。創建新行時,您還應該添加該功能。

$scope.addAnotherRow = function() { 
      $scope.gridData.push({ 
       'Consumption': '', 
       'ConversionQuantity': '', 
       getActualConsumption: function() { 
        return this.Consumption/this.ConversionQuantity; 
       } 
      }); 
     }; 

請注意,我剛剛複製的getActualConsumption您的實現 - 你應該做某種驗證,以確保你不被零獲得跳水的錯誤,並確保這兩個值實際數字

+0

謝謝。容易的事情,我不能考慮。對我感到羞恥。 – 2014-09-07 11:39:06

相關問題