根据 AngularJS 中的输入范围更新值

Updating a value based on a range of inputs in AngularJS

我在这里基本上想要实现的是,当用户在一系列文本字段中输入金额时,剩余金额会减少。

这些文本字段是由 angular 循环生成的,它是我需要更新的 remainingAmount 变量,因此,例如,如果新的剩余金额为 40,则用户在字段 1 中输入 10,然后剩余金额一路变成30直到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>

笨蛋:http://plnkr.co/edit/NmwTfGNC7jJyRL1kADCJ

尝试将输入绑定到您的模型。然后你可以计算输入之一的变化剩余:

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

看到这个plunker

一个没有验证或任何东西的简单示例(不确定你为什么将对象用作数组..所以我切换到使用数组 - 还将输入从 text 更改为 number 以避免重新解析数字,因为 angular 会将 属性 设置为字符串):

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