Angularjs (+ jQuery) - custom directive for auto-resize <textarea>
Angularjs - custom directive for auto-resize <textarea>. Some function of DOM needs jQuery.
by hugogo7646
HTML
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
This <textarea> will change its height to contain content.
<div ng-app="app" ng-controller="controller as ctrl">
<textarea textarea-auto-resizer ng-model="ctrl.text"></textarea>
</div>
JavaScript
angular.module("app", [])
.controller("controller", ["$scope", function($scope) {
var self = this;
self.text = "long words - long words - long words - long words - long words - long words - long words - long words - long words - long words - long words - long words - long words - long words - long words"
}])
.directive('textareaAutoResizer', ["$sce", function($sce) {
return {
link: function(scope, element, attrs, ngModel) {
autoResizeTextArea();
scope.$watch(attrs.ngModel, function(newValue, oldValue) {
autoResizeTextArea();
});
element.on("input", autoResizeTextArea);
function autoResizeTextArea(event) {
var dom = angular.element(element);
dom.css({
height: ""
});
if (dom.prop("scrollHeight") > dom.innerHeight()) {
//set dom height(without padding part) to scrollHeight - padding part
dom.height(dom.prop("scrollHeight") - (dom.innerHeight() - dom.height()));
}
}
}
};
}]);