Skip to content

Instantly share code, notes, and snippets.

@Tucker-Eric
Last active January 12, 2017 22:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Tucker-Eric/ce135c1e11c7be82add07c13461bb9e8 to your computer and use it in GitHub Desktop.
Save Tucker-Eric/ce135c1e11c7be82add07c13461bb9e8 to your computer and use it in GitHub Desktop.
Angular Column Total Directive
(function (angular) {
angular.module('column.totals', [])
.directive('columnTotal', ['$timeout', function ($timeout) {
function getOffset(elem) {
let offset = 0;
let prev = elem.previousElementSibling;
while (prev) {
offset++;
prev = prev.previousElementSibling;
}
return offset
}
return {
restrict: 'A',
link: function (scope, elem, attrs) {
const $el = elem[0];
const table = $el.parentNode.parentNode;
attrs.columnZeroValue = attrs.columnZeroValue || 0;
scope.$watch(attrs.columnTotal, calculateTotals);
function calculateTotals() {
$timeout(() => {
const column = getOffset($el);
$el.innerText = Array.from(table.children).reduce((total, row) => {
if (row.children[column] && !row.children[column].hasAttribute('column-total')) {
const val = parseInt(row.children[column].innerText);
return total + (Number.isNaN(val) ? 0 : val);
}
return total;
}, 0) || attrs.columnZeroValue;
}, 0);
}
}
}
}]);
})(angular);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment