Skip to content

Instantly share code, notes, and snippets.

@itsmunim
Created August 28, 2015 09:02
Show Gist options
  • Save itsmunim/e30eade39a9a1fcb8983 to your computer and use it in GitHub Desktop.
Save itsmunim/e30eade39a9a1fcb8983 to your computer and use it in GitHub Desktop.
Adjusts the height of a list based on top elements and bottom elements in any display.
'use strict';
angular.module('MunimDibosh.directives')
.directive('adjustListHeight', function ($timeout) {
return {
restrict: 'A',
link: function (scope, element) {
var parent, elemList, parentHeight, elemIndexOnDom;
// Watch for height changes
var _watchForHeightChange = function (elemList) {
angular.forEach(elemList, function (elem) {
scope.$watch(function () {
return elem.offsetHeight;
},
function (newValue, oldValue) {
if (newValue !== oldValue) {
_updateListHeight();
}
}
);
});
};
// Called initially; does setup
var _initOnDomLoad = function () {
parent = element.parent();
if (parent[0].nodeName && parent[0].nodeName.toLowerCase() === 'ng-include') {
parent = parent.parent();
}
elemList = parent.children();
parentHeight = parent.height();
elemIndexOnDom = _.findIndex(elemList, function (elem) {
return elem.className.indexOf('list-wrapper') > -1 || (elem.nodeName && elem.nodeName.toLowerCase() === 'ng-include' && elem.firstElementChild.className.indexOf('list-wrapper') > -1);
});
_watchForHeightChange(elemList);
_updateListHeight();
};
// Updates the actual height of the list wrapper
var _updateListHeight = function () {
var cumulativeHeight = 0;
for (var i = 0; i < elemIndexOnDom; i++) {
cumulativeHeight += elemList[i].offsetHeight;
}
if (parentHeight > cumulativeHeight) {
element.height(parentHeight - cumulativeHeight);
}
};
// Initially timeout ensures the calculation takes place after whole dom has been loaded
$timeout(_initOnDomLoad, 0);
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment