AngularJS ng-repeat with number inputs (updating min and max).
HTML
<body ng-app="myApp" ng-controller="MainCtrl">Remaining: {{getRemainder()}}
<br>
<div ng-repeat="option in options" ng-controller="OptionsCtrl">
{{option.name}}
<input type="number" min=0 ng-model="option.value">
<br>
</div>
</body>
JavaScript
var app = angular.module('myApp', []);
app.controller('MainCtrl', function ($scope) {
$scope.options = new Array(10);
$scope.options = [
{name: 'Input 1', value: 10},
{name: 'Input 2', value: 20},
{name: 'Input 3', value: 30},
{name: 'Input 4', value: 0},
{name: 'Input 5', value: 0},
{name: 'Input 6', value: 0}
];
$scope.max = 100;
$scope.getRemainder = function () {
var sum = 0;
// console.log('values: ' + $scope.options);
angular.forEach($scope.options, function (option) {
sum += option.value || 0;
});
return $scope.max - sum;
};
});
app.controller('OptionsCtrl', function ($scope) {
$scope.$watch('option.value', function (newValue, oldValue) {
var sum = 0;
angular.forEach($scope.options, function (option, j) {
if ($scope.$index !== j) {
sum += option.value;
}
});
console.log('sum: ' + sum);
if ($scope.max - sum < 0) {
$scope.options[$scope.$index].value = oldValue;
}
});
});