Last active
August 29, 2015 14:05
AngularJS Truncate Directive
This file contains hidden or 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
/** | |
* @example | |
* <p tuncate max-lines="3"> | |
* 8-bit street art brunch YOLO, crucifix PBR Banksy. | |
* Direct trade Bushwick art party letterpress, Cosby | |
* sweater selvage plaid pop-up forage meh you | |
* probably haven't heard of them. Food truck | |
* 90's sartorial locavore ugh seitan, | |
* shabby chic cardigan artisan. | |
* </p> | |
*/ | |
angular.module('textUtils', []) | |
.directive('truncate', function() { | |
return { | |
restrict: 'A', | |
scope: { | |
maxLines: '@' | |
}, | |
link: function(scope, elem, attr) { | |
var text = elem.text(), | |
split = text.split(/\s/), | |
minIndex = 0, | |
maxIndex = split.length - 1, | |
maxLines = scope.maxLines || 2, | |
lineHeight = elem.text('X').height(), | |
maxHeight = maxLines * lineHeight, | |
index; | |
var nextIndex = function() { | |
return Math.round( ( minIndex + (maxIndex - minIndex) ) / 2 ); | |
}; | |
var currentHeight = function() { | |
return elem.outerHeight(); | |
}; | |
var truncatedAt = function(idx) { | |
return split.slice(0, idx).join(' ').replace(/\W+$/, '') + '…'; | |
}; | |
elem.text(text); | |
if (currentHeight() > maxHeight) { | |
while (currentHeight() < maxHeight || currentHeight() > (maxHeight + lineHeight)) { | |
index = nextIndex(); | |
elem.text(truncatedAt(index)); | |
if (currentHeight() > maxHeight) { | |
maxIndex = index; | |
} else { | |
minIndex = index; | |
} | |
} | |
} | |
elem.text(truncatedAt(maxIndex--)); | |
while(currentHeight() > maxHeight) { | |
elem.text(truncatedAt(maxIndex)); | |
maxIndex--; | |
} | |
} | |
}; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment