Reputation: 1590
What I am essentially trying to achieve here is to have a remaining amount that decreases in amount as the user enters the amount in to a series of text fields.
These text fields are generated by an angular loop and its the remainingAmount var that I need to be updated, so if for example the fresh remaining amount if 40 then a user enters 10 into field 1 then the remaining amount becomes 30 all the way until 0.
<div class="row">
<div class="col text-center error">
<span ng-model="remainingAmount">{{ remainingAmount }}</span> left to distribute
</div>
</div>
</div>
<div class="list">
<div class="item item-button-right" ng-repeat="user in users">
{{ user.first_name }} {{ user.last_name }}
<span class="item-note">
<input type="text" />
</span>
</div>
</div>
Plunk: http://plnkr.co/edit/NmwTfGNC7jJyRL1kADCJ
Upvotes: 0
Views: 64
Reputation: 8055
A simple example with no validation or anything (not sure why you're using an object as an array .. so I switched to using an array - also changed the input from text
to number
to avoid having to re-parse the number since angular would set the property as string) :
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
var maxAmount = 40;
$scope.remainingAmount = maxAmount;
$scope.users = [
{'id':1, 'first_name':'Joe', 'last_name': 'Bloggs', amountUsed: 0},
{'id':2, 'first_name':'Chris', 'last_name': 'Scott', amountUsed: 0}
];
$scope.updateUsage = function(){
var totalUsed = 0;
for (var i = 0; i < $scope.users.length; i++) {
var u = $scope.users[i];
totalUsed += u.amountUsed;
}
$scope.remainingAmount = maxAmount - totalUsed;
}
});
Upvotes: 0
Reputation: 5825
Try to bind the inputs to your model. Then you could calculate the remaining on change of one of the inputs:
HTML:
<input type="text" ng-model="user.amount" ng-change="calc()" />
JS:
$scope.calc = function() {
var total = 0, user;
for (user in $scope.users) {
total += parseInt($scope.users[user].amount, 10) || 0;
}
$scope.remainingAmount = Math.max($scope.startAmount - total, 0);
}
See this plunker
Upvotes: 1