-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpartedInput.angular.js
87 lines (78 loc) · 3.53 KB
/
partedInput.angular.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
angular
.module("inputParted", [])
.directive("partedInput", function () {
return {
scope: {
size: "=?",
type: "=?",
styleClass: "=?",
styleIdPrefix: "=?",
regex: "=?"
},
require: ["ngModel"],
restrict: 'E',
link: function (scope, elem, attrs, ctrl) {
scope.size = scope.size || 4;
scope.type = scope.type || 'number';
scope.styleClass = scope.styleClass || 'parted-input';
scope.styleIdPrefix = scope.styleIdPrefix || 'input-part';
scope.arr = Array(scope.size);
var defaultVal = ctrl[0].$viewValue;
scope.partVal = typeof defaultVal === "number" || typeof defaultVal === "string"
? ("" + defaultVal).split("").map(readyArr)
: Array.isArray(defaultVal) ? defaultVal.map(readyArr) : [];
var defaultTextRegex = "[0-9]|[a-z]|[A-Z]";
var defaultNumberRegex = "[0-9]";
var isText = scope.type.toUpperCase() === "TEXT";
var regex = new RegExp(scope.regex || (isText ?
defaultTextRegex : defaultNumberRegex));
scope.$watch('partVal', function (newVal, oldVal) {
if (newVal && typeof newVal.join === 'function') {
ctrl[0].$setViewValue(newVal.join(""));
}
}, true);
scope.keydown = function (event, index) {
event = event.originalEvent || event;
event.preventDefault();
var element = angular.element(event.srcElement || event.currentTarget);
var isFirst = index === 0;
var isLast = index === (scope.size - 1);
switch (event.key.toUpperCase()) {
case "BACKSPACE":
case "DELETE":
scope.partVal[index] = "";
!isFirst && element[0].previousElementSibling.focus();
break;
case "TAB":
isLast ? element[0].blur() : element[0].nextElementSibling.focus();
break;
default:
event.key.length === 1 && regex.test(event.key) &&
((scope.partVal[index] = isText ? event.key : +event.key) &&
isLast && element[0].blur() || element[0].nextElementSibling.focus());
break;
}
return false;
}
scope.pasteFun = function (event) {
event = event.originalEvent || event;
event.preventDefault();
if (!event || !event.clipboardData) {
return false;
}
var text = event.clipboardData.getData("text") || "";
scope.partVal = isText ? text.split("") : text.split("").map(convertToNumber);
return false;
}
function convertToNumber(str) {
var num = +str;
return isNaN(num) ? null : num;
}
function readyArr(val) {
var char = ("" + val).substr(0, 1);
return isText ? char : convertToNumber(char);
}
},
template: "<input type='{{type}}' id='{{styleIdPrefix}}-{{$index}}' ng-class='styleClass' ng-paste='pasteFun($event)' ng-keyup='keydown($event, $index)' ng-repeat='id in arr track by $index' ng-model='partVal[$index]' />"
}
});