Skip to content

Instantly share code, notes, and snippets.

@codfish
Last active February 12, 2018 09:02
Show Gist options
  • Save codfish/c9e21570a0bc3bee26f6 to your computer and use it in GitHub Desktop.
Save codfish/c9e21570a0bc3bee26f6 to your computer and use it in GitHub Desktop.
AngularJS Equal Height columns directive.
'use strict';
/**
* Equal Heights
*
* Attach this directive to the parent/wrapping element of
* a bunch of elements that are columns. This directive will
* calculate the height of every direct child (one level down)
* then set all of them to be the height of the tallest one.
*
* @example
<ul data-equal-heights>
<li>column1</li>
<li>column2</li>
<li>column3</li>
</ul>
*
* @ngInject
*/
function EqualHeightsDirective($timeout) {
function link($scope, $element, attrs) {
$timeout(function() {
var $children = $element.children(),
currentMaxHeight = 0,
numImagesLoaded = 0,
$images = $element.find('img'),
imageCount = $images.length;
if (imageCount > 0) {
angular.forEach($images, function(image) {
if (image.complete) {
numImagesLoaded++;
}
});
}
if (numImagesLoaded === imageCount) {
angular.forEach($children, function(child) {
var childHeight = $(child).outerHeight();
if (childHeight > currentMaxHeight) {
currentMaxHeight = childHeight;
}
});
// set heights
$children.css({height: currentMaxHeight});
}
});
}
return {
restrict: 'A',
scope: {},
link: link
};
}
angular
.module('ui.equalHeights', [])
.directive('equalHeights', EqualHeightsDirective)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment