Skip to content

Instantly share code, notes, and snippets.

@mtford90
Last active August 29, 2015 14:18
Show Gist options
  • Save mtford90/f09924dcaf329aafd142 to your computer and use it in GitHub Desktop.
Save mtford90/f09924dcaf329aafd142 to your computer and use it in GitHub Desktop.
resizeToFit angular directive
angular.module('farm4trade')
.directive('resizeToFit',
function() {
return {
restrict: 'EA',
replace: false,
transclude: true,
link: function(scope, elem) {
var $parent = $(elem[0]),
$span = $parent.find('.resize'),
fontSize = parseInt($parent.css('font-size')),
originalFontSize = fontSize;
function setFontSize(fontSize) {
$span.css('font-size', fontSize.toString() + 'px');
}
function resize() {
setFontSize(originalFontSize);
fontSize = originalFontSize;
if ($parent) {
var parentWidth = $parent.width();
if (parentWidth) {
while ($span.width() >= parentWidth) {
fontSize--;
setFontSize(fontSize);
}
}
}
}
resize();
scope.$watch(function() {
return $parent.width();
}, resize);
scope.$watch(function () {
return elem.text().length;
}, resize);
},
template: '<span style="display: inline-block; font-size: 50px;" class="resize" ng-transclude/>'
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment