Skip to content

Instantly share code, notes, and snippets.

@rlindgren
Last active August 29, 2015 14:08
Show Gist options
  • Save rlindgren/8e64deb3fe06bb485ef9 to your computer and use it in GitHub Desktop.
Save rlindgren/8e64deb3fe06bb485ef9 to your computer and use it in GitHub Desktop.
auto-expanding textarea angular directive. possibly the simplest implementation of this behavior for modern browsers.
angular.module('kExpandingTextarea', [])
.directive('kAutoExpandTextarea', function () {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, el, attrs, ctrls) {
if (!(/textarea/i.test(el[0].tagName))) return;
var handler = function handler (e) {
el[0].style.height = (attrs.minHeight || '36px');
el[0].style.height = el[0].scrollHeight + 'px';
};
// works better with both listeners. means twice the computational overhead...
var watcher = scope.$watch(function () { return el.val() }, handler);
el.on('keyup', handler);
scope.$on('$destroy', function () {
watcher(); // release watcher
el.off('keyup', handler);
});
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment