JSFiddle - React, Tailwind, and code Playground
HTML
<div class="form" data-ng-app="example">
<div class="control-group" data-ng-controller="ExampleCtrl">
<label for="example">Some textarea</label>
<textarea autogrow ng-model="text"></textarea>
</div>
</div>
CSS
.form {
width: 400px;
margin: 20px auto;
padding: 20px;
background: #f7f7f7;
}
textarea {
width: 100%;
display: block;
resize: none;
padding: 20px;
font-size: 16px;
font-family: 'Arial',
line-height: 1.5;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
JavaScript
angular.module('example', [])
.controller('ExampleCtrl', function ($scope) {
$scope.text = 'Some example text';
})
.directive('autogrow', function () {
// styles that influence on text
var props = [
'webkitBoxSizing', '-webkit-box-sizing', 'padding', 'font', 'width', 'textIndent',
'whiteSpace', 'wordSpacing', 'wordWrap', 'textAlign'
];
return {
restrict: 'A',
require: 'ngModel',
replace: false,
link: function ($scope, $element, attrs, ngModel) {
var $copy = angular.element('<div></div>'),
minHeight = $element[0].clientHeight,
computedStyles = window.getComputedStyle($element[0]),
stylesheets = $copy[0].style,
val;
// copy styles of original element
props.forEach(function (prop) {
if (computedStyles.hasOwnProperty(prop)) {
stylesheets[prop] = computedStyles[prop];
}
});
// make out copy element invisible
$copy.css({
height: 'auto',
position: 'absolute',
top: '-9999px',
left: '-9999px'
});
angular.element(document.body).append($copy);
function update() {
function times (string, number) {
for (var i = 0, r = ''; i < number; i++) {
r += string;
}
return r;
}
val = $element.val().replace(/</g, '<')
.replace(/>/g, '>')
.replace(/&/g, '&')
.replace(/\n$/, '<br/> ')
.replace(/\n/g, '<br/>')
.replace(/\s{2,}/g, function(space) { return times(' ', space.length - 1) + ' ' });
$copy.html(val);
$element.css('height',...