Skip to content

Instantly share code, notes, and snippets.

@danmartens
Last active August 29, 2015 14:05
Show Gist options
  • Save danmartens/eb94a7b3eb5824e45d0c to your computer and use it in GitHub Desktop.
Save danmartens/eb94a7b3eb5824e45d0c to your computer and use it in GitHub Desktop.
AngularJS Truncate Directive
/**
* @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+$/, '') + '&hellip;';
};
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