-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathangularjs-autogrow.js
97 lines (87 loc) · 3.45 KB
/
angularjs-autogrow.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
(function(){
'use strict';
angular.module('angularjs-autogrow', []).directive('autogrow', ['$window', function($window){
return {
link: function($scope, $element, $attrs){
/**
* Default settings
*/
$scope.attrs = {
rows: 1,
maxLines: 999
};
/**
* Merge defaults with user preferences
*/
for(var i in $scope.attrs){
if($attrs[i]){
$scope.attrs[i] = parseInt($attrs[i]);
}
}
/**
* Calculates the vertical padding of the element
* @returns {number}
*/
$scope.getOffset = function(){
var style = $window.getComputedStyle($element[0], null),
props = ['paddingTop', 'paddingBottom'],
offset = 0;
for(var i=0; i<props.length; i++){
offset += parseInt(style[props[i]]);
}
return offset;
};
/**
* Sets textarea height as exact height of content
* @returns {boolean}
*/
$scope.autogrowFn = function(){
var newHeight = 0, hasGrown = false;
if(($element[0].scrollHeight - $scope.offset) > $scope.maxAllowedHeight){
$element[0].style.overflowY = 'scroll';
newHeight = $scope.maxAllowedHeight;
}
else {
$element[0].style.overflowY = 'hidden';
$element[0].style.height = 'auto';
newHeight = $element[0].scrollHeight - $scope.offset;
hasGrown = true;
}
$element[0].style.height = newHeight + 'px';
return hasGrown;
};
$scope.offset = $scope.getOffset();
$scope.lineHeight = ($element[0].scrollHeight / $scope.attrs.rows) - ($scope.offset / $scope.attrs.rows);
$scope.maxAllowedHeight = ($scope.lineHeight * $scope.attrs.maxLines) - $scope.offset;
$scope.$watch($attrs.ngModel, $scope.autogrowFn);
// Extract css properties to spy on
var spyProps = $attrs.autogrow ? $attrs.autogrow.split(',') : [];
angular.forEach(spyProps, function(property) {
// Set a watcher on each property
$scope.$watch(
function() {
return $element.css(property);
},
styleChangedCallBack
);
});
/**
*
* @param newValue
* @param oldValue
*/
function styleChangedCallBack(newValue, oldValue) {
if (newValue !== oldValue) {
$scope.autogrowFn();
}
}
/**
* Auto-resize when there's content on page load
*/
if($element[0].value != ''){
$scope.autogrowFn();
}
}
}
}]);
})();