Created
December 18, 2013 03:47
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
}) | |
} | |
}; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
great alternative to angular-elastic if you're using inputs instead of text areas. Thanks!