FrenkyB FrenkyB - 25 days ago 6
AngularJS Question

ng-change on a table cell updates all cells

I have a table with columns, where I need to calculate values on other cells on table change event. I would like to do this with ng-change, so change is seen immediately. Problem is, that I don't know how to properly use ng-model - if used in one row, it will be used in all rows, so each row is recalculated, which I don't want. I would like to update just one row at the time.

Angular demands ng-model, where ng-change is used. How to properly use ng-change, where there are several rows in table?

I can do this with jQuery onchange event, but I already have controller on HTML, so I would like to do all in angular.

Example of one of the rows:

<tr class="jtable-data-row jtable-row-even"
data-record-key="110000001"><td>110000001</td>
<td><input type="text"
ng-change="RecalculateValues($event);" ng-model="Quantity" value="1"></td>
<td><input type="text"
ng-change="RecalculateValues($event);" ng-model="Bruto" value="7.15"></td>
<td><input type="text"
ng-change="RecalculateValues($event);" ng-model="Neto" class="cellContent" class="cellContent" value="17"></td>
</tr>


EDIT:

Plunker here is showing my problem - cells are not updated, although ng-change event is wired to input values.

Answer

You are going about it the wrong way.

Example:

<tr>
  <td>{{total}}</td>
  <td>
    <input type="text" ng-change="calculate()" ng-model="quantity">
  </td>
  <td>
    <input type="text" ng-change="calculate()" ng-model="bruto">
  </td>
</tr>

Controller:

$scope.quantity = 1;
$scope.bruto = 7.5;
$scope.total = 0;

$scope.calculate = function() {
  $scope.total = $scope.quantity * $scope.bruto;
}

$scope.calculate();

If you have more than one table row, you will need to have an array of objects, each object containing a quantity and bruto and a total.

<tr ng-repeat="n in valuesArray">
  <td>{{n.total}}</td>
  <td>
    <input type="text" ng-change="calculate($index)" ng-model="n.quantity">
  </td>
  <td>
    <input type="text" ng-change="calculate($index)" ng-model="n.bruto">
  </td>
</tr>

Controller:

$scope.valuesArray = [
  {quantity: 1, bruto: 7.5, total: 0},
  {quantity: 1, bruto: 7.5, total: 0},
  {quantity: 1, bruto: 7.5, total: 0},
];

$scope.calculate = function(index) {
  $scope.valuesArray[index].total = $scope.valuesArray[index].quantity * $scope.valuesArray[index].bruto;
}