[英]How to Sum a Json Array value in AngularJS ng-repeat
I want to sum the product count which are added dynamically using JSON array. 我想总结使用JSON数组动态添加的产品数量。
<tr ng-repeat="(key,val) in form.products">
<td>{{ProductName(key)}}</td>
<td >
<input type="text" name="products" ng-model="form.products[key]" class="form-control">
</td>
</tr>
How can I get the sum of products in the above example? 在上面的示例中,如何获得乘积之和?
presuming the value you want to sum is in a property called 'price': 假设您要求和的值位于名为“ price”的属性中:
{{_(form.products).mapValues('price').sum()}}
you may need to get lodash into your scope first. 您可能需要先将lodash纳入您的范围。 In the controller, something like:
在控制器中,如下所示:
scope._ = _;
or this approach 或这种方法
you are using an ' object with properties ' instead of ' an array of objects ', that is why you cant use your example above , $scope.products.length;... . 您使用的是“ 带有属性 的对象 ”,而不是“ 对象 数组 ”,这就是为什么您不能使用上面的示例$ scope.products.length; ...的原因 。
Your product object with its properties : 您的产品对象及其属性 :
$scope.products ={
"1":"20",//property 1 with value 20
"2":"35",//property 2 with value 35
"3":"150"//property 3 with value 150
}
The data Object (object with properties as you have it) : 数据对象(具有属性的对象) :
$scope.myData = {"1":120,"2":250,"3":500};
Function that iterates into object's properties and sum the price : 迭代到对象属性并求和的函数 :
//read object properties and sum price
$scope.calculateSum = function(data){
var sum=0;
var counter=0;
for (var property in data) {
if (data.hasOwnProperty(property)) {
sum += data[property];
counter++;
}
}
return sum;
};
Function that iterates into object properties and count the products 迭代到对象属性并计算乘积的函数
//read object properties and count the products
$scope.countProducts = function(data){
var counter=0;
for (var property in data) {
if (data.hasOwnProperty(property)) {
counter++;
}
}
return counter;
};
Into your HTML template: 进入您的HTML模板:
<table>
<tr ng-repeat="(key,value) in myData track by $index">
<td>
<input type="text" name="id" ng-model="key" class="form-control">
</td>
<td>
<input type="text" name="price" ng-model="value" class="form-control">
</td>
</tr>
<tr>
<td>Products: {{countProducts(myData)}}</td>
<td>Sum: {{calculateSum(myData)}}</td>
</tr>
</table>
I have done a live example that counts the products and also sum the products price: http://plnkr.co/edit/FmJhvV?p=preview 我已经完成了一个实时示例,该示例对产品进行计数并对产品价格进行求和: http : //plnkr.co/edit/FmJhvV?p=preview
Hope helps, good luck. 希望有帮助,祝你好运。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.