我有一个对象数组,其中每个对象都有一个百分比值。用户可以输入任何值。如何将百分比值的总和限制为 100?例如:
[ {"name":"Pradeesh","contribution":4534,"percentage":40}, {"name":"Kumar","contribution":3425,"percentage":30}, {"name":"Rajesh","contribution":1234,"percentage":20}, {"name":"Romeo","contribution":3434,"percentage":10}]
在这种情况下,如果任何人尝试更改任何用户的百分比值,它应该抛出一个错误,指出总数超过 100。
最佳答案
考虑到您的对象数组是 myObject
,您可以在该对象上添加一个观察者并检查总百分比是否超过 100
$scope.$watch(function(){return myObject;},function (newValue,oldValue) {
var totalPercentage = 0;
newValue.forEach(function(value){
totalPercentage += value.percentage;
});
if(totalPercentage > 100){
myObject = oldValue;
throw "Total Percentage Exceeds 100";
}
},true);
关于javascript - Angular JS : How to stop sum of complex filed values crossing a limit?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40997821/