计算AngularJS ng repeat中重复元素的和
下面的脚本使用计算AngularJS ng repeat中重复元素的和,angularjs,angularjs-ng-repeat,Angularjs,Angularjs Ng Repeat,下面的脚本使用ng repeat显示购物车。对于数组中的每个元素,它显示项目名称、金额和小计(product.price*product.quantity) 计算重复元素总价的最简单方法是什么 <table> <tr> <th>Product</th> <th>Quantity</th> <th>Price</th> </tr&g
ng repeat
显示购物车。对于数组中的每个元素,它显示项目名称、金额和小计(product.price*product.quantity
)
计算重复元素总价的最简单方法是什么
<table>
<tr>
<th>Product</th>
<th>Quantity</th>
<th>Price</th>
</tr>
<tr ng-repeat="product in cart.products">
<td>{{product.name}}</td>
<td>{{product.quantity}}</td>
<td>{{product.price * product.quantity}} €</td>
</tr>
<tr>
<td></td>
<td>Total :</td>
<td></td> <!-- Here is the total value of my cart -->
</tr>
</table>
产品
量
价格
{{product.name}
{{product.quantity}
{{product.price*product.quantity}}
总数:
在模板中
<td>Total: {{ getTotal() }}</td>
Total:{{getTotal()}
内部控制器
$scope.getTotal = function(){
var total = 0;
for(var i = 0; i < $scope.cart.products.length; i++){
var product = $scope.cart.products[i];
total += (product.price * product.quantity);
}
return total;
}
$scope.getTotal=function(){
var合计=0;
对于(变量i=0;i<$scope.cart.products.length;i++){
var product=$scope.cart.products[i];
合计+=(产品.价格*产品.数量);
}
返回总数;
}
这也适用于过滤器和正常列表。首先要为列表中所有值的总和创建一个新的过滤器,并为总量的总和提供解决方案。
详细代码检查它
angular.module(“sampleApp”,[])
.filter('sumOfValue',函数(){
返回函数(数据,键){
if(角度未定义(数据)| |角度未定义(键))
返回0;
var总和=0;
角度.forEach(数据、函数(值){
sum=sum+parseInt(值[键],10);
});
回报金额;
}
}).filter('totalSumPriceQty',函数(){
返回函数(数据,键1,键2){
如果(角度.isUndefined(数据)| |角度.isUndefined(键1)| |角度.isUndefined(键2))
返回0;
var总和=0;
角度.forEach(数据、函数(值){
sum=sum+(parseInt(值[key1],10)*parseInt(值[key2],10));
});
回报金额;
}
}).controller(“采样控制器”,函数($scope){
$scope.items=[
{“id”:1,“细节”:“test11”,“数量”:2,“价格”:100},
{“id”:2,“细节”:“test12”,“数量”:5,“价格”:120},
{“id”:3,“细节”:“test3”,“数量”:6,“价格”:170},
{“id”:4,“细节”:“test4”,“数量”:8,“价格”:70}
];
});
搜寻
身份证件
细节
量
价格
全部的
{{item.id}
{{item.details}
{{item.quantity}
{{item.price}}
{{item.quantity*item.price}}
{{resultValue}sumOfValue:'quantity'}
{{resultValue}sumOfValue:'price'}
{{resultValue | totalSumPriceQty:'quantity':'price'}
检查这个我对RajaShilpa的答案进行了一些扩展。您可以使用如下语法:
{{object | sumOfTwoValues:'quantity':'products.productWeight'}}
以便可以访问对象的子对象。以下是过滤器的代码:
.filter('sumOfTwoValues', function () {
return function (data, key1, key2) {
if (typeof (data) === 'undefined' || typeof (key1) === 'undefined' || typeof (key2) === 'undefined') {
return 0;
}
var keyObjects1 = key1.split('.');
var keyObjects2 = key2.split('.');
var sum = 0;
for (i = 0; i < data.length; i++) {
var value1 = data[i];
var value2 = data[i];
for (j = 0; j < keyObjects1.length; j++) {
value1 = value1[keyObjects1[j]];
}
for (k = 0; k < keyObjects2.length; k++) {
value2 = value2[keyObjects2[k]];
}
sum = sum + (value1 * value2);
}
return sum;
}
});
.filter('sumOfTwoValues',函数(){
返回功能(数据、键1、键2){
if(typeof(data)=='undefined'| | typeof(key1)=='undefined'| | typeof(key2)=='undefined'){
返回0;
}
var keyObjects1=key1.split('.');
var keyObjects2=key2.split('.');
var总和=0;
对于(i=0;i
这是我的解决方案
甜美简单的自定义过滤器:
(但只涉及简单的值和,而不是和积,我已经编写了sumProduct
filter并将其作为编辑添加到本文中)
编辑:sumProduct
这是sumProduct
filter,它接受任意数量的参数。作为参数,它从输入数据中接受属性的名称,并且可以处理嵌套属性(用点标记的嵌套:property.nested
)
- 传递零参数返回输入数据的长度
- 只传递一个参数将返回该属性值的简单总和
- 传递更多参数将返回所传递属性值的乘积之和(属性的标量和)
angular.module('myApp', [])
.filter('sumProduct', function() {
return function (input) {
var i = input instanceof Array ? input.length : 0;
var a = arguments.length;
if (a === 1 || i === 0)
return i;
var keys = [];
while (a-- > 1) {
var key = arguments[a].split('.');
var property = getNestedPropertyByKey(input[0], key);
if (isNaN(property))
throw 'filter sumProduct can count only numeric values';
keys.push(key);
}
var total = 0;
while (i--) {
var product = 1;
for (var k = 0; k < keys.length; k++)
product *= getNestedPropertyByKey(input[i], keys[k]);
total += product;
}
return total;
function getNestedPropertyByKey(data, key) {
for (var j = 0; j < key.length; j++)
data = data[key[j]];
return data;
}
}
})
angular.module('myApp',[])
.filter('sumProduct',function(){
返回函数(输入){
var i=数组的输入实例?input.length:0;
var a=arguments.length;
如果(a==1 | i==0)
返回i;
var键=[];
while(a-->1){
var key=arguments[a]。拆分('.');
var property=getNestedPropertyByKey(输入[0],键);
if(伊斯南(财产))
抛出“filter sumProduct只能计算数值”;
按键。按(键);
}
var合计=0;
而(我--){
var乘积=1;
对于(var k=0;k
意识到这一点很久以前就有了答案,但想发布未呈现的不同方法 使用
ng init
统计您的总数。这样,您就不必在HTML中迭代,也不必在控制器中迭代。在这个场景中
angular.module('myApp', [])
.filter('total', function () {
return function (input, property) {
var i = input instanceof Array ? input.length : 0;
// if property is not defined, returns length of array
// if array has zero length or if it is not an array, return zero
if (typeof property === 'undefined' || i === 0) {
return i;
// test if property is number so it can be counted
} else if (isNaN(input[0][property])) {
throw 'filter total can count only numeric values';
// finaly, do the counting and return total
} else {
var total = 0;
while (i--)
total += input[i][property];
return total;
}
};
})
angular.module('myApp', [])
.filter('sumProduct', function() {
return function (input) {
var i = input instanceof Array ? input.length : 0;
var a = arguments.length;
if (a === 1 || i === 0)
return i;
var keys = [];
while (a-- > 1) {
var key = arguments[a].split('.');
var property = getNestedPropertyByKey(input[0], key);
if (isNaN(property))
throw 'filter sumProduct can count only numeric values';
keys.push(key);
}
var total = 0;
while (i--) {
var product = 1;
for (var k = 0; k < keys.length; k++)
product *= getNestedPropertyByKey(input[i], keys[k]);
total += product;
}
return total;
function getNestedPropertyByKey(data, key) {
for (var j = 0; j < key.length; j++)
data = data[key[j]];
return data;
}
}
})
<tr>
<th>Product</th>
<th>Quantity</th>
<th>Price</th>
</tr>
<tr ng-repeat="product in cart.products">
<td>{{product.name}}</td>
<td>{{product.quantity}}</td>
<td ng-init="itemTotal = product.price * product.quantity; controller.Total = controller.Total + itemTotal">{{itemTotal}} €</td>
</tr>
<tr>
<td></td>
<td>Total :</td>
<td>{{ controller.Total }}</td> // Here is the total value of my cart
</tr>
// random controller snippet
function yourController($scope..., blah) {
var vm = this;
vm.Total = 0;
}
angular.module('myApp').filter('total', ['$parse', function ($parse) {
return function (input, property) {
var i = input instanceof Array ? input.length : 0,
p = $parse(property);
if (typeof property === 'undefined' || i === 0) {
return i;
} else if (isNaN(p(input[0]))) {
throw 'filter total can count only numeric values';
} else {
var total = 0;
while (i--)
total += p(input[i]);
return total;
}
};
}]);
{{data | total:'values[0].value'}}
<table>
<tr ng-repeat="item in items" ng-init="setTotals(item)">
<td>{{item.name}}</td>
<td>{{item.quantity}}</td>
<td>{{item.unitCost | number:2}}</td>
<td>{{item.total | number:2}}</td>
</tr>
<tr class="bg-warning">
<td>Totals</td>
<td>{{invoiceCount}}</td>
<td></td>
<td>{{invoiceTotal | number:2}}</td>
</tr>
</table>
$scope.setTotals = function(item){
if (item){
item.total = item.quantity * item.unitCost;
$scope.invoiceCount += item.quantity;
$scope.invoiceTotal += item.total;
}
}
.filter('total', function () {
return function (input, property) {
var i = input instanceof Array ? input.length : 0;
if (typeof property === 'undefined' || i === 0) {
return i;
} else if (typeof property === 'function') {
var total = 0;
while (i--)
total += property(input[i]);
return total;
} else if (isNaN(input[0][property])) {
throw 'filter total can count only numeric values';
} else {
var total = 0;
while (i--)
total += input[i][property];
return total;
}
};
})
$scope.calcItemTotal = function(v) { return v.price*v.quantity; };
<td>Total: {{ totalSum }}</td>
$scope.totalSum = Object.keys(cart.products).map(function(k){
return +cart.products[k].price;
}).reduce(function(a,b){ return a + b },0);
$scope.totalSum = Object.keys(cart.products)
.map(k => +cart.products[k].price)
.reduce((a, b) => a + b);
<tbody ng-init="total = 0">
<tr ng-repeat="product in products">
<td>{{ product.name }}</td>
<td>{{ product.quantity }}</td>
<td ng-init="$parent.total = $parent.total + (product.price * product.quantity)">${{ product.price * product.quantity }}</td>
</tr>
<tr>
<td>Total</td>
<td></td>
<td>${{ total }}</td>
</tr>
</tbody>
$scope.bySchool = alasql('SELECT School, SUM(Cost) AS Cost from ? GROUP BY School',[restResults]);
<b class="text-primary">Total Amount: ${{ data.allTicketsTotalPrice() }}</b>
app.controller('myController', function ($http) {
var vm = this;
vm.allTicketsTotalPrice = function () {
var totalPrice = 0;
angular.forEach(vm.ticketTotalPrice, function (value, key) {
totalPrice += parseFloat(value);
});
return totalPrice.toFixed(2);
};
});
<table ng-init="ResetTotalAmt()">
<tr>
<th>Product</th>
<th>Quantity</th>
<th>Price</th>
</tr>
<tr ng-repeat="product in cart.products">
<td ng-init="CalculateSum(product)">{{product.name}}</td>
<td>{{product.quantity}}</td>
<td>{{product.price * product.quantity}} €</td>
</tr>
<tr>
<td></td>
<td>Total :</td>
<td>{{cart.TotalAmt}}</td> // Here is the total value of my cart
</tr>
</table>
$scope.cart.TotalAmt = 0;
$scope.CalculateSum= function (product) {
$scope.cart.TotalAmt += (product.price * product.quantity);
}
//It is enough to Write code $scope.cart.TotalAmt =0; in the function where the cart.products get allocated value.
$scope.ResetTotalAmt = function (product) {
$scope.cart.TotalAmt =0;
}
ng-repeat="_ in [ products ]"
ng-repeat="_ in [ [ products, search ] ]"
<td>Total: {{ calculateTotal() }}</td>
$scope.calculateVAT = function () {
return $scope.cart.products.reduce((accumulator, currentValue) => accumulator + (currentValue.price * currentValue.quantity), 0);
};
$scope.total = 0;
var aCart = new CartService();
$scope.addItemToCart = function (product) {
aCart.addCartTotal(product.Price);
};
$scope.showCart = function () {
$scope.total = aCart.getCartTotal();
};
app.service("CartService", function () {
Total = [];
Total.length = 0;
return function () {
this.addCartTotal = function (inTotal) {
Total.push( inTotal);
}
this.getCartTotal = function () {
var sum = 0;
for (var i = 0; i < Total.length; i++) {
sum += parseInt(Total[i], 10);
}
return sum;
}
};
});
.filter('sumColumn', function(){
return function(dataSet, columnToSum){
let sum = 0;
for(let i = 0; i < dataSet.length; i++){
sum += parseFloat(dataSet[i][columnToSum]) || 0;
}
return sum;
};
})
<th>{{ dataSet | sumColumn: 'keyInObjectToSum' }}</th>
**Angular 6: Grand Total**
**<h2 align="center">Usage Details Of {{profile$.firstName}}</h2>
<table align ="center">
<tr>
<th>Call Usage</th>
<th>Data Usage</th>
<th>SMS Usage</th>
<th>Total Bill</th>
</tr>
<tr>
<tr *ngFor="let user of bills$">
<td>{{ user.callUsage}}</td>
<td>{{ user.dataUsage }}</td>
<td>{{ user.smsUsage }}</td>
<td>{{user.callUsage *2 + user.dataUsage *1 + user.smsUsage *1}}</td>
</tr>
<tr>
<th> </th>
<th>Grand Total</th>
<th></th>
<td>{{total( bills$)}}</td>
</tr>
</table>**
**Controller:**
total(bills) {
var total = 0;
bills.forEach(element => {
total = total + (element.callUsage * 2 + element.dataUsage * 1 + element.smsUsage * 1);
});
return total;
}
<div ng-controller="MainCtrl as mc">
<ul>
<li ng-repeat="n in [1,2,3,4]" ng-init="mc.sum = ($first ? 0 : mc.sum) + n">{{n}}</li>
<li>sum : {{mc.sum}}</li>
</ul>
</div>