pBlackmouth pBlackmouth - 2 months ago 10
AngularJS Question

Angularjs Input text value depends from another input text and viceversa

I have an array of data that show in a table, that table is editable, and want the fields are dependent on each other.

How I can do that by changing the percentage of a cell, change the amount for that row and vice versa, when you change the amount, also change the percentage? always verifying not exceeding 100% of the sum of the percentages, and the sum of the amounts not exceeding the total amount.



angular
.module("app", [])
.controller("appController", function ($scope) {

$scope.Data = [
{
Percent: 25.0,
Value: 1000.0
},
{
Percent: 25.0,
Value: 1000.0
},
{
Percent: 25.0,
Value: 1000.0
},
{
Percent: 25.0,
Value: 1000.0
}
];
$scope.TotalAmount = 4000.0;
});

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<link rel="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" type="text/css" />

</head>
<body ng-app="app">

<div class="container" ng-controller="appController">
Total amount: {{TotalAmount}}
<table class="table table-striped">
<tr><th>Percent</th><th>Value</th></tr>
<tr ng-repeat="invoice in Data">
<td><input type="number" ng-model="invoice.Percent" /></td>
<td><input type="number" ng-model="invoice.Value" /></td>
</tr>
</table>
</div>

</body>
</html>




Answer

You can use ng-change for each input(just like @Pravin Erande said in comments).

I have made a SAMPLE FIDDLE for you(without any calculations)

<tr ng-repeat="invoice in Data">
                <td><input type="number" ng-model="invoice.Percent" ng-change="valueChanged($index,invoice.Percent,invoice.Value)" /></td>
                <td><input type="number" ng-model="invoice.Value" ng-change="valueChanged($index,invoice.Percent,invoice.Value)" /></td>
            </tr>



$scope.valueChanged= function(index,precent,value)
  {
    console.log("Index changed "+index+" percent "+precent+" value "+value);
    $scope.Data[index].Percent = 50; // Assign after calculation
$scope.Data[index].Value = 2000; // Assign after calculation
  }

You can create a function and pass the $index to that function and update the $scope.Data accordingly after calculation