I
I
IvanKalinin2015-08-11 04:56:40
JavaScript
IvanKalinin, 2015-08-11 04:56:40

How to dynamically change textarea height in AngularJS directive?

All the best.
Please tell me how to dynamically change the height of a textarea using AngularJS depending on the content.
I made this directive:

.directive('textareaHeight', [
        function () {
            return {
                restrict: 'A',
                require: 'ngModel',
                link: function postLink(scope, element, attrs, ngModel) {
                    element.bind('input propertychange', function () {
                        
                        if (angular.element(element[0]).height() < element[0].scrollHeight) {
                            angular.element(element[0]).css('height', element[0].scrollHeight + 2).css('transition', 'height 200ms ease')
                        }
                    });
                }
            };
        }]);

Everything is beautiful, but it only works to increase the height. If you remove a couple of lines, then the height will not decrease.
Or maybe there is a way to find out the number of line breaks in order to work with the height from there.
ps I do not want to install third-party directives and scripts. I would like to cope with standard AngularJS tools

Answer the question

In order to leave comments, you need to log in

1 answer(s)
_
_ _, 2015-08-11
@IvanKalinin

Create a div with the same text styles as the textarea, make it position: absolute, stumble offscreen. When entering text in a textarea, insert the same text into this div, measure its height and resp. set height for textarea.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question