Advertisement
evilbloodydemon

Untitled

May 26th, 2015
293
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  
  2. .directive('angularMask', function () {
  3.     return {
  4.         restrict: 'A',
  5.         link: function ($scope, el, attrs) {
  6.             var format = attrs.angularMask;
  7.  
  8.             function replaceAt(s, index, character) {
  9.                 return s.substr(0, index) + character + s.substr(index+character.length);
  10.             }
  11.  
  12.             function clearByMask(val) {
  13.                 var v = val || '';
  14.                 for(var i = 0; i < Math.min(format.length, val.length); i++) {
  15.                     if (format[i] != '_' || !v[i].match(/\d/)) {
  16.                         v = replaceAt(v, i, ' ');
  17.                     }
  18.                 }
  19.  
  20.                 return v.replace(/\s/g, '');
  21.             }
  22.  
  23.             function mask(o) {
  24.                 var value = clearByMask(o.value);
  25.                 var newValue = '';
  26.                 for (var valueIndex = 0, formatIndex = 0; formatIndex < format.length;) {
  27.                     if (format[formatIndex] != '_') {
  28.                         newValue += format[formatIndex];
  29.                     } else {
  30.                         if (value[valueIndex] != undefined) {
  31.                             newValue += value[valueIndex];
  32.                             valueIndex++;
  33.                         } else {
  34.                             break;
  35.                         }
  36.                     }
  37.                     formatIndex++;
  38.                 }
  39.                 o.value = newValue;
  40.             }
  41.  
  42.             el.bind('keyup keydown', function (e) {
  43.                 var keyList = [8, 37, 39, 46];
  44.                 if (keyList.indexOf(e.keyCode) == -1) {
  45.                     mask(this);
  46.                 }
  47.             });
  48.         }
  49.     };
  50. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement