Вычисление суммы повторяющихся элементов в AngularJS ng-repeat
Ниже приведена script корзина с помощью 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>
Ответы
Ответ 1
В шаблоне
<td>Total: {{ getTotal() }}</td>
В контроллере
$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;
}
Ответ 2
Это также работает как фильтр, так и обычный список. Первым делом необходимо создать новый фильтр для суммы всех значений из списка, а также дать решение для суммы общего количества. Детально проверяйте код ссылки скрипача.
angular.module("sampleApp", [])
.filter('sumOfValue', function () {
return function (data, key) {
if (angular.isUndefined(data) || angular.isUndefined(key))
return 0;
var sum = 0;
angular.forEach(data,function(value){
sum = sum + parseInt(value[key], 10);
});
return sum;
}
}).filter('totalSumPriceQty', function () {
return function (data, key1, key2) {
if (angular.isUndefined(data) || angular.isUndefined(key1) || angular.isUndefined(key2))
return 0;
var sum = 0;
angular.forEach(data,function(value){
sum = sum + (parseInt(value[key1], 10) * parseInt(value[key2], 10));
});
return sum;
}
}).controller("sampleController", function ($scope) {
$scope.items = [
{"id": 1,"details": "test11","quantity": 2,"price": 100},
{"id": 2,"details": "test12","quantity": 5,"price": 120},
{"id": 3,"details": "test3","quantity": 6,"price": 170},
{"id": 4,"details": "test4","quantity": 8,"price": 70}
];
});
<div ng-app="sampleApp">
<div ng-controller="sampleController">
<div class="col-md-12 col-lg-12 col-sm-12 col-xsml-12">
<label>Search</label>
<input type="text" class="form-control" ng-model="searchFilter" />
</div>
<div class="col-md-12 col-lg-12 col-sm-12 col-xsml-12">
<div class="col-md-2 col-lg-2 col-sm-2 col-xsml-2">
<h4>Id</h4>
</div>
<div class="col-md-4 col-lg-4 col-sm-4 col-xsml-4">
<h4>Details</h4>
</div>
<div class="col-md-2 col-lg-2 col-sm-2 col-xsml-2 text-right">
<h4>Quantity</h4>
</div>
<div class="col-md-2 col-lg-2 col-sm-2 col-xsml-2 text-right">
<h4>Price</h4>
</div>
<div class="col-md-2 col-lg-2 col-sm-2 col-xsml-2 text-right">
<h4>Total</h4>
</div>
<div ng-repeat="item in resultValue=(items | filter:{'details':searchFilter})">
<div class="col-md-2 col-lg-2 col-sm-2 col-xsml-2">{{item.id}}</div>
<div class="col-md-4 col-lg-4 col-sm-4 col-xsml-4">{{item.details}}</div>
<div class="col-md-2 col-lg-2 col-sm-2 col-xsml-2 text-right">{{item.quantity}}</div>
<div class="col-md-2 col-lg-2 col-sm-2 col-xsml-2 text-right">{{item.price}}</div>
<div class="col-md-2 col-lg-2 col-sm-2 col-xsml-2 text-right">{{item.quantity * item.price}}</div>
</div>
<div colspan='3' class="col-md-8 col-lg-8 col-sm-8 col-xsml-8 text-right">
<h4>{{resultValue | sumOfValue:'quantity'}}</h4>
</div>
<div class="col-md-2 col-lg-2 col-sm-2 col-xsml-2 text-right">
<h4>{{resultValue | sumOfValue:'price'}}</h4>
</div>
<div class="col-md-2 col-lg-2 col-sm-2 col-xsml-2 text-right">
<h4>{{resultValue | totalSumPriceQty:'quantity':'price'}}</h4>
</div>
</div>
</div>
</div>
проверьте эту ссылку Fiddle
Ответ 3
Понимая, что это давно ответили, но хотел опубликовать другой подход, не представленный...
Используйте ng-init
для подсчета общей суммы. Таким образом, вам не нужно выполнять итерацию в HTML и выполнять итерацию в контроллере. В этом сценарии я считаю, что это более чистое/более простое решение. (Если логика подсчета была более сложной, я определенно рекомендовал бы переместить логику в контроллер или службу, если это необходимо.)
<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>
Конечно, в вашем контроллере просто укажите/инициализируйте поле Total
:
// random controller snippet
function yourController($scope..., blah) {
var vm = this;
vm.Total = 0;
}
Ответ 4
Вы можете рассчитать общее количество внутри ng-repeat
:
<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>
Проверьте результат здесь: http://plnkr.co/edit/Gb8XiCf2RWiozFI3xWzp?p=preview
Если результат автоматического обновления: http://plnkr.co/edit/QSxYbgjDjkuSH2s5JBPf?p=preview (Спасибо - VicJordan)
Ответ 5
Это мое решение
сладкий и простой пользовательский фильтр:
(но связанный только с простой суммой значений, а не с суммами, я создал фильтр sumProduct
и добавил его как редактирование в этот пост).
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;
}
};
})
EDIT: sumProduct
Это фильтр sumProduct
, он принимает любое количество аргументов. В качестве аргумента он принимает имя свойства из входных данных и может обрабатывать вложенное свойство (вложенность помечена точкой: property.nested
);
- Передача нулевого аргумента возвращает длину входных данных.
- Передача только одного аргумента возвращает простую сумму значений этих свойств.
- При переходе большего количества аргументов возвращается сумма произведений значений переданных свойств (скалярная сумма свойств).
здесь JS Fiddle и код
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;
}
}
})
Ответ 6
Простое решение
Вот простое решение. Дополнительный цикл не требуется.
часть HTML
<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>
Script Часть
$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;
}
Ответ 7
Это простой способ сделать это с помощью ng-repeat и ng-init для агрегирования всех значений и расширения модели с помощью свойства item.total.
<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>
Директива ngInit вызывает функцию set total для каждого элемента.
Функция setTotals в контроллере вычисляет общее количество элементов. Он также использует переменные scope-invoiceCount и invoiceTotal для суммирования (суммирования) количества и общего количества для всех элементов.
$scope.setTotals = function(item){
if (item){
item.total = item.quantity * item.unitCost;
$scope.invoiceCount += item.quantity;
$scope.invoiceTotal += item.total;
}
}
для получения дополнительной информации и демонстрации по этой ссылке:
http://www.ozkary.com/2015/06/angularjs-calculate-totals-using.html
Ответ 8
Другой способ решения этого вопроса, простирающийся от Vaclav answer, чтобы решить этот конкретный расчет - то есть расчет по каждой строке.
.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; };
Вы использовали бы {{ datas|total:calcItemTotal|currency }}
в своем HTML-коде. Это имеет то преимущество, что не вызывается для каждого дайджеста, потому что он использует фильтры и может использоваться для простых или сложных итогов.
JSFiddle
Ответ 9
Я предпочитаю элегантные решения
В шаблоне
<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);
Если вы используете ES2015 (он же ES6)
$scope.totalSum = Object.keys(cart.products)
.map(k => +cart.products[k].price)
.reduce((a, b) => a + b);
Ответ 10
вот мое решение этой проблемы:
<td>Total: {{ calculateTotal() }}</td>
скрипт
$scope.calculateVAT = function () {
return $scope.cart.products.reduce((accumulator, currentValue) => accumulator + (currentValue.price * currentValue.quantity), 0);
};
уменьшение будет выполняться для каждого продукта в массиве продуктов. Накопитель - это общая накопленная сумма, currentValue - текущий элемент массива, а 0 в последнем - начальное значение.
Ответ 11
Вы можете попробовать использовать сервисы angular js, у меня это сработало... приведя фрагменты кода ниже
Код контроллера:
$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;
}
};
});
Ответ 12
Вы можете использовать пользовательский угловой фильтр, который принимает массив объектов набора данных и ключ в каждом объекте для суммирования. Затем фильтр может вернуть сумму:
.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>
Ответ 13
Я немного расширил ответ 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;
}
});
Ответ 14
Взятие Вацлава отвечает и делает его более Angular -like:
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'}}
Ответ 15
В html
<b class="text-primary">Total Amount: ${{ data.allTicketsTotalPrice() }}</b>
в javascript
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);
};
});
Ответ 16
Ответ Huy Nguyen почти есть. Чтобы заставить его работать, добавьте:
ng-repeat="_ in [ products ]"
... к строке с ng-init. В списке всегда есть один элемент, поэтому Angular будет повторять блок ровно один раз.
Демо-версия Zybnek, использующая фильтрацию, может быть запущена, добавив:
ng-repeat="_ in [ [ products, search ] ]"
См. http://plnkr.co/edit/dLSntiy8EyahZ0upDpgy?p=preview.
Ответ 17
**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;
}
Ответ 18
Прочитав все ответы здесь - как обобщить сгруппированную информацию, я решил пропустить все это и просто загрузил одну из SQL-библиотек SQL. Я использую alasql, да, это занимает несколько секунд больше времени загрузки, но экономит бесчисленное количество времени при кодировании и отладке. Теперь, чтобы группировать и суммировать(), я просто использую
$scope.bySchool = alasql('SELECT School, SUM(Cost) AS Cost from ? GROUP BY School',[restResults]);
Я знаю, что это звучит как немного напыщенно на angular/js, но на самом деле SQL решил это еще 30 лет назад, и нам не нужно было повторно изобретать его в браузере.