Skip to content

Instantly share code, notes, and snippets.

@miguelfrmn
Created August 30, 2013 11:28
Show Gist options
  • Save miguelfrmn/6388941 to your computer and use it in GitHub Desktop.
Save miguelfrmn/6388941 to your computer and use it in GitHub Desktop.
/**
* Angular JS directive for autorezising text inside an element
* Usage:
* <input type="text" ng-model="text">
* <p style="font-size: 30px; border: red 1px solid; width: 200px; height: 20px;" autofit="text"><span>{{text}}</span></p>
*/
app.directive('autofit', function(){
return function(scope, element, attrs){
var span = element.find('span:visible:first');
var maxHeight = element.height();
var maxWidth = element.width();
var originalFontSize = parseInt(element.css('font-size').replace('px',''),10);
function resize(){
var fontSize = originalFontSize;
var textHeight = span.height();
var textWidth = span.width();
do {
element.css('font-size', fontSize + 'px');
//span.css('line-height', fontSize + 'px');
element.css('line-height', fontSize + 'px');
textHeight = span.height();
textWidth = span.width();
fontSize--;
} while ((textHeight > maxHeight || textWidth > maxWidth) && fontSize > 3);
}
if(attrs.autofit){
var parts = attrs.autofit.split(',');
for(var i in parts){
scope.$watch(parts[i], function(){
resize();
});
}
}
resize();
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment