Last active
January 12, 2017 22:38
-
-
Save Tucker-Eric/ce135c1e11c7be82add07c13461bb9e8 to your computer and use it in GitHub Desktop.
Angular Column Total Directive
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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]) { | |
return total; | |
} | |
const val = parseInt(row.children[column].innerText); | |
return total + (Number.isNaN(val) ? 0 : val); | |
}, 0) || attrs.columnZeroValue; | |
}, 0); | |
} | |
} | |
} | |
}]); | |
})(angular); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment