Skip to content

Instantly share code, notes, and snippets.

@mbenford
Created December 18, 2013 03:47
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mbenford/8016984 to your computer and use it in GitHub Desktop.
Save mbenford/8016984 to your computer and use it in GitHub Desktop.
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
Copy link

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