forked from rwaltenberg/angular-money-mask
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rw-money-mask.js
91 lines (73 loc) · 2.1 KB
/
rw-money-mask.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
(function () {
'use strict';
angular
.module('rw.moneymask', [])
.directive('moneyMask', moneyMask);
moneyMask.$inject = ['$filter', '$window'];
function moneyMask($filter, $window) {
var directive = {
require: 'ngModel',
link: link,
restrict: 'A',
scope: {
model: '=ngModel'
}
};
return directive;
function link(scope, element, attrs, ngModelCtrl) {
var display, cents;
ngModelCtrl.$render = function () {
display = $filter('number')(cents / 100, 2);
if (attrs.moneyMaskPrepend) {
display = attrs.moneyMaskPrepend + ' ' + display;
}
if (attrs.moneyMaskAppend) {
display = display + ' ' + attrs.moneyMaskAppend;
}
element.val(display);
}
scope.$watch('model', function onModelChange(newValue) {
newValue = parseFloat(newValue) || 0;
if (newValue !== cents) {
cents = Math.round(newValue * 100);
}
ngModelCtrl.$viewValue = newValue;
ngModelCtrl.$render();
});
element.on('keydown', function (e) {
if ((e.which || e.keyCode) === 8) {
cents = parseInt(cents.toString().slice(0, -1)) || 0;
ngModelCtrl.$setViewValue(cents / 100);
ngModelCtrl.$render();
scope.$apply();
e.preventDefault();
}
});
element.on('keypress', function (e) {
var key = e.which || e.keyCode;
if(key === 9) {
return true;
}
if (key >= 96 && key <= 105) {
key -= 48; // Numpad keys
}
var char = String.fromCharCode(key);
e.preventDefault();
if (char.search(/[0-9\-]/) === 0) {
cents = parseInt(cents + char);
}
else {
return false;
}
if(e.currentTarget.selectionEnd != e.currentTarget.selectionStart) {
ngModelCtrl.$setViewValue(parseInt(char) / 100);
}
else {
ngModelCtrl.$setViewValue(cents / 100);
}
ngModelCtrl.$render();
scope.$apply();
})
}
}
})();