Skip to content

Instantly share code, notes, and snippets.

@dgieselaar
Created March 18, 2014 20:03
Show Gist options
  • Save dgieselaar/9628280 to your computer and use it in GitHub Desktop.
Save dgieselaar/9628280 to your computer and use it in GitHub Desktop.
/*global angular,_*/
(function ( ) {
angular.module('Zaaksysteem')
.directive('zsCrudTableAutoSize', [ '$window', '$timeout', function ( $window, $timeout ) {
return {
link: function ( scope, element/*, attrs*/ ) {
function setAutoWidth ( ) {
var rows = element[0].querySelectorAll('.table-row'),
totalWidthByCol = {},
numColumns = Number.MAX_VALUE,
i,
l,
totalSize,
minCellSize,
percLeft;
if(!rows.length) {
return;
}
function resetColumnSize ( ) {
_.each(rows[0].children, function ( element ) {
angular.element(element).css('width', '');
});
}
function getColumnSize ( num ) {
var width = 0,
row,
i,
l,
cell,
el;
for(i = 0, l = rows.length; i < l; ++i) {
row = rows[i];
cell = row.children[num];
if(i === 0) {
continue;
}
if(cell) {
el = cell.children.length ? cell.children[0] : null;
width = Math.max(width, el.scrollWidth);
}
}
return width;
}
_.each(rows, function ( row ) {
numColumns = Math.min(row.children.length, numColumns);
});
resetColumnSize();
for(i = 0, l = numColumns; i < l; ++i) {
totalWidthByCol[i] = getColumnSize(i);
}
totalSize = _.reduce(totalWidthByCol, function ( sum, num ) {
return sum + num;
}, 0);
minCellSize = 100 / numColumns / 2;
percLeft = 100 - minCellSize * numColumns;
_.each(totalWidthByCol, function ( width, index ) {
var cell = rows[0].children[index];
cell.style.width = (parseInt(width/totalSize * percLeft, 10) + minCellSize) + '%';
});
}
scope.$on('zs.crud.item.change', function ( ) {
$timeout(function ( ) {
setAutoWidth();
});
});
scope.$watch('columns', function ( ) {
$timeout(function ( ) {
setAutoWidth();
});
}, true);
}
};
}]);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment