-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathangular-elastic-input.js
More file actions
79 lines (64 loc) · 3.03 KB
/
Copy pathangular-elastic-input.js
File metadata and controls
79 lines (64 loc) · 3.03 KB
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
/**
* angular-elastic-input
* A directive for AngularJS which automatically resizes the width of input field according to the content, while typing.
* @author: Jacek Pulit <jacek.pulit@gmail.com>
* @license: MIT License
*/
'use strict';
angular.module('puElasticInput', []).directive('puElasticInput', ['$document', '$window', function($document, $window) {
var wrapper = angular.element('<div style="position:fixed; top:-999px; left:0;"></div>');
angular.element($document[0].body).append(wrapper);
function setMirrorStyle(mirror, element, attrs) {
var style = $window.getComputedStyle(element[0]);
var defaultMaxWidth = style.maxWidth === 'none' ? element.parent().prop('clientWidth') : style.maxWidth;
element.css('minWidth', attrs.puElasticInputMinwidth || style.minWidth);
element.css('maxWidth', attrs.puElasticInputMaxwidth || defaultMaxWidth);
angular.forEach(['fontFamily', 'fontSize', 'fontWeight', 'fontStyle',
'letterSpacing', 'textTransform', 'wordSpacing'], function(value) {
mirror.css(value, style[value]);
});
mirror.css('paddingLeft', style.textIndent);
if (style.boxSizing === 'border-box') {
angular.forEach(['paddingLeft', 'paddingRight',
'borderLeftStyle', 'borderLeftWidth',
'borderRightStyle', 'borderRightWidth'], function(value) {
mirror.css(value, style[value]);
});
} else if (style.boxSizing === 'padding-box') {
angular.forEach(['paddingLeft', 'paddingRight'], function(value) {
mirror.css(value, style[value]);
});
}
}
return {
restrict: 'A',
link: function postLink(scope, element, attrs) {
// Disable trimming inputs by default
attrs.$set('ngTrim', attrs.ngTrim === 'true' ? 'true' : 'false');
var mirror = angular.element('<span style="white-space:pre;"></span>');
setMirrorStyle(mirror, element, attrs);
wrapper.append(mirror);
function update() {
var defaultDelta = 1;
if (element[0].tagName === "SELECT") {
var index = element[0].selectedIndex;
defaultDelta = 8;
mirror.text((index > -1 && element[0].options[index].text) || attrs.placeholder || '');
} else if (element[0].tagName === "INPUT") {
mirror.text(element.val() || attrs.placeholder || '');
}
var delta = parseInt(attrs.puElasticInputWidthDelta) || defaultDelta;
element.css('width', mirror.prop('offsetWidth') + delta + 'px');
}
update();
if (attrs.ngModel) {
scope.$watch(attrs.ngModel, update);
} else {
element.on('keydown keyup focus input propertychange change', update);
}
scope.$on('$destroy', function() {
mirror.remove();
});
}
};
}]);