在ng-grid中添加带有计算字段的新行

时间:2014-09-01 23:29:54

标签: javascript angularjs angular-ui 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 Code ..

$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时,它无法计算实际消耗量。

那么,我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:1)

您只为初始数据上的每一行附加getActualConsumption函数。创建新行时,还应添加该功能。

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

请注意我刚刚复制了您getActualConsumption的实施内容 - 您可能应该进行某种验证,以确保您不会因潜水而获得错误由零确保两个值都是实际数字