Skip to content

Instantly share code, notes, and snippets.

@mbenford mbenford/autosize.js
Created Dec 18, 2013

Embed
What would you like to do?
Autosize directive for AngularJS. Resizes an input field automatically so its content is always visible. http://plnkr.co/edit/iodg4SqKBXL0V6ZJmRue
app.directive('autosize', function($document) {
return {
require: 'ngModel',
link: function(scope, element, attrs, ctrl) {
var placeholder, span, resize;
placeholder = element.attr('placeholder') || '';
span = angular.element('<span></span>');
span[0].style.cssText = getComputedStyle(element[0]).cssText;
span.css('display', 'none')
.css('visibility', 'hidden')
.css('width', 'auto');
$document.find('body').append(span);
resize = function(value) {
if (value.length < placeholder.length) {
value = placeholder;
}
span.text(value);
span.css('display', '');
try {
element.css('width', span.prop('offsetWidth') + 'px');
}
finally {
span.css('display', 'none');
}
};
ctrl.$parsers.unshift(function(value) {
resize(value);
return value;
});
ctrl.$formatters.unshift(function(value) {
resize(value);
return value;
})
}
};
});
@phonyphonecall

This comment has been minimized.

Copy link

commented Aug 26, 2014

great alternative to angular-elastic if you're using inputs instead of text areas. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.