StackOverflow_23790489: angularjs-calculate-dynamically-subtotals-for-each-different-percentage
Illustration of answer to http://stackoverflow.com/questions/23790489/angularjs-calculate-dynamically-subtotals-for-each-different-percentage.
by karthick Chandran
HTML
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js"></script>
<table ng-controller="SubTotalCtrl">
<thead>
<tr><th ng-repeat="(key, th) in head">{{th}}</th></tr>
</thead>
<tbody>
<tr ng-repeat="row in body">
<td >{{row.a}}</td>
<td >{{row.b}}</td>
<td >{{row.c}}</td>
</tr>
</tbody>
<tfoot>
<tr ng-repeat="(perc, sum) in grouppedByPercentage()">
<td></td>
<td><span>Subtotal for {{perc}}%</span></td>
<td>{{sum * perc / 100.0}}</td>
</tr>
</tfoot>
</table>
JavaScript
angular
.module('myApp', [])
.controller('SubTotalCtrl', function ($scope) {
// data
$scope.head = {
a: "S. No",
b: "Change Description",
c: "Estimated Effor (in Person Days)"
};
$scope.body = [{
a: "1",
b: "Feedback Form",
c: "10"
}, {
a: "2",
b: "0",
c: "5"
}, {
a: "3",
b: "10",
c: "20"
}];
$scope.grouppedByPercentage = function () {
var groups = {};
$scope.body.forEach(function (row) {
['b', 'c'].forEach(function (key) {
var perc = row[key];
if (perc === '0') { return; } // ignore 0 percentage
if (!groups[perc]) {
groups[perc] = 0;
}
groups[perc] += parseInt(row.a);
// use `parseFloat()` if you want decimal points
});
});
return groups;
};
});