Skip to content

Instantly share code, notes, and snippets.

@Tucker-Eric
Last active January 12, 2017 22:38

Revisions

  1. Tucker-Eric revised this gist Jan 12, 2017. 1 changed file with 5 additions and 4 deletions.
    9 changes: 5 additions & 4 deletions columnTotals.js
    Original file line number Diff line number Diff line change
    @@ -25,11 +25,12 @@
    $timeout(() => {
    const column = getOffset($el);
    $el.innerText = Array.from(table.children).reduce((total, row) => {
    if (!row.children[column]) {
    return total;
    if (row.children[column] && !row.children[column].hasAttribute('column-total')) {
    const val = parseInt(row.children[column].innerText);
    return total + (Number.isNaN(val) ? 0 : val);
    }
    const val = parseInt(row.children[column].innerText);
    return total + (Number.isNaN(val) ? 0 : val);
    return total;

    }, 0) || attrs.columnZeroValue;
    }, 0);
    }
  2. Tucker-Eric created this gist Jan 12, 2017.
    39 changes: 39 additions & 0 deletions columnTotals.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,39 @@
    (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);