Skip to content

Instantly share code, notes, and snippets.

Last active April 29, 2016 02:12
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
.directive('autoSize', ['$timeout', function($timeout) {
return function (scope, element, attr, ctrl) {
var minHeight;
var $shadowtx = angular.element("<textarea class='" + attr['class'] + "'></textarea>");
//add to element parent
element.css({resize: "none"}).parent().css({ position: "relative" });
var update = function (addtext) {
$shadowtx.val(element.val() + (addtext ? addtext: ''));
element.css('height', Math.max($shadowtx[0].scrollHeight, minHeight) + 'px');
element.bind('keydown', function (event) {
var keyc = event.keyCode || event.which;
if (keyc == 13) {
}).bind('keyup', function (event) {
var keyc = event.keyCode || event.which;
if ((keyc == 46) || (keyc==8)) { //delete, backspace, not fired by scope.$watch
minHeight = element[0].offsetHeight;
position: 'absolute',
top: -10000,
left: -10000,
resize: 'none',
width: element.width(),
height: element.height()
}, 0);
scope.$watch(attr['ngModel'], function(v){update();});
Copy link

symonny commented Apr 29, 2016

based on

my adjusted version added below makes sure that there are no extra spaces added under the text

  • I used $timeout to make sure the shadow element's sizes are set after the current element is rendered and we have the correct size of the text
  • For textarea style i have set a height / min-height:
textarea{resize: none; box-sizing: content-box; height: auto; overflow: hidden;}
textarea.form-control{ min-height: 16px; height: 16px;  width: 100%;  }

  • Sample usage

<textarea class="form-control word-wrap" auto-size placeholder="Set Location…" ng-model="item.address" ui-focus="isInTabFocus(listIndex, 1)" tabindex="{{getTabIndex(listIndex,1)}}"></textarea>

  • sample result

screen shot 2016-04-28 at 6 58 26 pm

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment