Calculation logic within editable table row

237 views Asked by At

I have a table like this:

<tr class="data-row" ng-repeat="item in model.Invoice.InvoiceItemData">
        <td>
            <input type="text" name="itemServiceTitle" ng-model="item.ServiceTitle" />
        </td>
        <td>
            <input type="text" name="itemQuantity" ng-model="item.Quantity"/>
        </td>
        <td>
            <input type="text" name="itemPricePerDimension" ng-model="item.PricePerDimension" />
        </td>
        <td>
            <input type="text" name="itemDeliveryCost" ng-model="item.DeliveryCost" readonly="readonly" />
        </td> ...

and I need to calculate each itemDeliveryCost by formula

item.DeliveryCost = item.Quantity * item.PricePerDimension

Question is - what is the best approach to do this? Notice that cahges for item.Quantity and item.PricePerDimension must be reflected in item.DeliveryCost dynamically.

2

There are 2 answers

4
Rakesh Chand On

Inside your api success call you can do following

angular.forEach($scope.model.Invoice.InvoiceItemData, function (item) {
    item.DeliveryCost = item.Quantity * item.PricePerDimension;
});

You will get calculated values in view..

If you want to change values after getting data, then above approach won't work but for that you need to call a method on value change of quantity and dimention like following

  <input type="text" name="itemQuantity" ng-model="item.Quantity"  
     ng-blur="deliveryCostChanging(item)"/>
  <input type="text" name="itemPricePerDimension"   
    ng-model="item.PricePerDimension" ng-blur="deliveryCostChanging(item)"/>


$scope.deliveryCostChanging = function(item){
     item.DeliveryCost = item.Quantity * item.PricePerDimension;
};
0
Mistalis On

As DeliveryCost = Quantity * Price, I would suggest to update DeliveryCost each time Quantity or Price is changed. It is exactly the use of ng-change:

<input type="text" ng-model="item.Quantity" ng-change="updateCost()"/>

<input type="text" ng-model="item.PricePerDimension" ng-change="updateCost()"/>

<input type="text" ng-model="item.DeliveryCost"/>

Then, define in your controller updateCost() function:

$scope.updateCost = function() {
    $scope.item.DeliveryCost = $scope.item.Quantity * $scope.item.PricePerDimension;
}