Angular.filter('total')
HTML
<div ng-app="myApp" ng-controller="myController">
<table border="1">
<thead>
<tr>
<th>Quantity</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="data in datas">
<td>{{ data.stock.quantity }}</td>
<td>{{ data.price|currency }}</td>
</tr>
</tbody>
<tfoot>
<tr>
<!-- here is the magic -->
<th colspan="2"> Total {{ datas|sumProduct:'price':'stock.quantity' }}</th>
</tr>
</tfoot>
</table>
</div>
JavaScript
var myApp = angular.module('myApp', []);
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;
}
}
})
.controller('myController', ['$scope',
function($scope) {
$scope.datas = [
{
price: 55.12,
stock: {
quantity: 1
}
},
{
price: 12.00,
stock: {
quantity: 5
}
},
{
price: 15.45,
stock: {
quantity: 13
}
},
{
price: 5.50,
stock: {
quantity: 7
}
},
];
}]);