forked from fiestah/angular-money-directive
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathangular-money-directive.js
95 lines (83 loc) · 2.55 KB
/
angular-money-directive.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
/**
* Heavily adapted from the `type="number"` directive in Angular's
* /src/ng/directive/input.js
*/
angular.module('fiestah.money', [])
.directive('money', function () {
'use strict';
var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))\s*$/;
function isUndefined(value) {
return typeof value == 'undefined';
}
function isEmpty(value) {
return isUndefined(value) || value === '' || value === null || value !== value;
}
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, el, attr, ctrl) {
function round(num) {
return Math.round(num * 100) / 100;
}
var min = parseFloat(attr.min) || 0;
// Returning NaN so that the formatter won't render invalid chars
ctrl.$parsers.push(function(value) {
// Allow "-" inputs only when min < 0
if (value === '-') {
ctrl.$setValidity('number', false);
return (min < 0) ? -0 : NaN;
}
var empty = isEmpty(value);
if (empty || NUMBER_REGEXP.test(value)) {
ctrl.$setValidity('number', true);
return value === '' ? null : (empty ? value : parseFloat(value));
} else {
ctrl.$setValidity('number', false);
return NaN;
}
});
ctrl.$formatters.push(function(value) {
return isEmpty(value) ? '' : '' + value;
});
var minValidator = function(value) {
if (!isEmpty(value) && value < min) {
ctrl.$setValidity('min', false);
return undefined;
} else {
ctrl.$setValidity('min', true);
return value;
}
};
ctrl.$parsers.push(minValidator);
ctrl.$formatters.push(minValidator);
if (attr.max) {
var max = parseFloat(attr.max);
var maxValidator = function(value) {
if (!isEmpty(value) && value > max) {
ctrl.$setValidity('max', false);
return undefined;
} else {
ctrl.$setValidity('max', true);
return value;
}
};
ctrl.$parsers.push(maxValidator);
ctrl.$formatters.push(maxValidator);
}
// Round off to 2 decimal places
ctrl.$parsers.push(function (value) {
return value ? round(value) : value;
});
ctrl.$formatters.push(function (value) {
return value ? value.toFixed(2) : value;
});
el.bind('blur', function () {
var value = ctrl.$modelValue;
if (value) {
ctrl.$viewValue = round(value).toFixed(2);
ctrl.$render();
}
});
}
};
});