如何在 AngularJS ng-repeat中对 Json 数组值求和
How to Sum a Json Array value in AngularJS ng-repeat
我想对使用 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>
如何获取上述示例中的产品总和?
使用 lodash
假设您要求和的值位于名为"price"的属性中:
{{_(form.products).mapValues('price').sum()}}
您可能需要先将 Lodash 纳入您的范围。 在控制器中,如下所示:
scope._ = _;
或者这种方法
您使用的是"具有属性的对象"而不是"对象数组",这就是为什么您不能使用上面的示例,$scope.products.length;...。
您的产品对象及其属性:
$scope.products ={
"1":"20",//property 1 with value 20
"2":"35",//property 2 with value 35
"3":"150"//property 3 with value 150
}
数据对象(具有您拥有的属性的对象):
$scope.myData = {"1":120,"2":250,"3":500};
迭代对象属性并对价格求和的函数:
//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;
};
迭代对象属性并计算乘积的函数
//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;
};
进入您的 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>
我做了一个活生生的例子,计算产品并汇总产品价格:http://plnkr.co/edit/FmJhvV?p=preview
希望有帮助,祝你好运。
相关文章:
- 需要帮助设置json数组
- 如何使用 node.js 比较两个 json 数组
- 根据id将json数组组合为一个json数组
- 如何创建JSON数组
- 如何将package.json数组传递给grunt.js
- 访问json数组中的对象
- JSON数组数据返回Undefined
- 如何向JSON数组动态添加属性
- 如何从json数组中获取特定值
- 从多维嵌套json数组创建下拉列表
- 在ListView中添加JSON数组中存储的图像-ReactNative
- jquery在json数组中循环
- 将 JSON 数组解析为 JavaScript 数组
- 如何在php中读取没有任何键的JSON数组
- 如何在Jquery中迭代JSON数组
- 如何在cycle js中从JSON数组创建组件
- 如何使用jquery返回php-json数组对象
- JSON数组转换为JS对象数组
- 使用System从C#集合创建JSON数组.网状物剧本序列化
- 使用Underscore.js修改json数组中所选元素的更有效方法