1 | 'use strict'; |
---|
2 | var tlaGenerics = angular.module('tlaGenerics', []); |
---|
3 | |
---|
4 | tlaGenerics.directive('autosizeTextarea', ['$window', '$timeout', |
---|
5 | |
---|
6 | function($window, $timeout) { |
---|
7 | function resizeTextArea(elm) { |
---|
8 | var textarea = elm[0]; |
---|
9 | var offset = !$window.opera ? (textarea.offsetHeight - textarea.clientHeight) : (textarea.offsetHeight + parseInt($window.getComputedStyle(textarea, null).getPropertyValue('border-top-width'))); |
---|
10 | elm.css('height', 'auto'); |
---|
11 | elm.css('height', (textarea.scrollHeight + offset) + 'px'); |
---|
12 | } |
---|
13 | |
---|
14 | return function(scope, element, attrs) { |
---|
15 | //resize the text area when the browser window is resized |
---|
16 | angular.element($window).bind('resize', function(event) { |
---|
17 | resizeTextArea(element); |
---|
18 | }); |
---|
19 | //resize textarea when the model changes |
---|
20 | scope.$watch(attrs.ngModel, function(newValue, oldValue) { |
---|
21 | if (newValue !== oldValue && (typeof newValue == 'string' || newValue instanceof String)) { |
---|
22 | //if textarea height is 0, wait for the DOM to be ready |
---|
23 | if (element[0].clientHeight === 0) { |
---|
24 | element.ready(function() { |
---|
25 | //do not resize if textarea height is still 0 after the DOM is ready (textarea is hidden) |
---|
26 | if (element[0].clientHeight !== 0) |
---|
27 | resizeTextArea(element); |
---|
28 | }); |
---|
29 | } else |
---|
30 | resizeTextArea(element); |
---|
31 | } |
---|
32 | }); |
---|
33 | //resize textare when autosizeTextarea.resize event is broadcasted |
---|
34 | scope.$on('autosizeTextarea.resize', function(event) { |
---|
35 | element.ready(function() { |
---|
36 | resizeTextArea(element); |
---|
37 | }); |
---|
38 | }); |
---|
39 | }; |
---|
40 | } |
---|
41 | ]); |
---|