Skip to content

Instantly share code, notes, and snippets.

@symonny
Last active April 29, 2016 02:12
Show Gist options
  • Save symonny/9246314ad5fd530fe0670e5d2ca8c369 to your computer and use it in GitHub Desktop.
Save symonny/9246314ad5fd530fe0670e5d2ca8c369 to your computer and use it in GitHub Desktop.
angular-textarea-autosize
.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
angular.element(element.parent()[0]).append($shadowtx);
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) {
update("\n");
}
}).bind('keyup', function (event) {
var keyc = event.keyCode || event.which;
if ((keyc == 46) || (keyc==8)) { //delete, backspace, not fired by scope.$watch
update();
}
});
$timeout(function(){
minHeight = element[0].offsetHeight;
$shadowtx.css({
position: 'absolute',
top: -10000,
left: -10000,
resize: 'none',
width: element.width(),
height: element.height()
});
update();
}, 0);
scope.$watch(attr['ngModel'], function(v){update();});
}
}]);
@symonny
Copy link
Author

symonny commented Apr 29, 2016

based on https://gist.github.com/thomseddon/4703968

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