Search code examples
javascriptangularjsangularjs-ng-repeatangular-ngmodel

Updating a value based on a range of inputs in AngularJS


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


Solution

  • 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) :

    plunkr

    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;
        }
    });