Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- .directive('angularMask', function () {
- return {
- restrict: 'A',
- link: function ($scope, el, attrs) {
- var format = attrs.angularMask;
- function replaceAt(s, index, character) {
- return s.substr(0, index) + character + s.substr(index+character.length);
- }
- function clearByMask(val) {
- var v = val || '';
- for(var i = 0; i < Math.min(format.length, val.length); i++) {
- if (format[i] != '_' || !v[i].match(/\d/)) {
- v = replaceAt(v, i, ' ');
- }
- }
- return v.replace(/\s/g, '');
- }
- function mask(o) {
- var value = clearByMask(o.value);
- var newValue = '';
- for (var valueIndex = 0, formatIndex = 0; formatIndex < format.length;) {
- if (format[formatIndex] != '_') {
- newValue += format[formatIndex];
- } else {
- if (value[valueIndex] != undefined) {
- newValue += value[valueIndex];
- valueIndex++;
- } else {
- break;
- }
- }
- formatIndex++;
- }
- o.value = newValue;
- }
- el.bind('keyup keydown', function (e) {
- var keyList = [8, 37, 39, 46];
- if (keyList.indexOf(e.keyCode) == -1) {
- mask(this);
- }
- });
- }
- };
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement