Skip to content

Instantly share code, notes, and snippets.

@msandrini
Created February 20, 2015 18:51
Show Gist options
  • Save msandrini/f2633a2a13d03a8d9798 to your computer and use it in GitHub Desktop.
Save msandrini/f2633a2a13d03a8d9798 to your computer and use it in GitHub Desktop.
Post Mask directive
<div ng-app="sample"
ng-controller="Sample">
Enter a number:
<input data-post-mask
ng-model="val"
data-pattern-find="(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})"
data-pattern-replace="$1.$2.$3/$4-$5"
data-trigger-length="14">
</div>

Post Mask directive

Magical directive that takes a field and converts it to a input=number while editing, and after editing (on blur event) formats it into a user-defined format.

A Pen by Marcos Sandrini on CodePen.

License.

var a = angular.module('sample',[]).
controller('Sample',function(){ });
/*
POST MASK Directive
Requires:
ng-model = variable (as usual)
pattern-find = regex in text form to separate parts
pattern-replace = replacement string for regex
trigger-length = length of the number-only input
*/
a.directive('postMask', function () {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, el, attrs, ngModel) {
el[0].addEventListener('focus', function () {
el[0].type = 'number';
var valorAtual = String(ngModel.$viewValue||'');
ngModel.$setViewValue((valorAtual || '').replace(/[\.|\-|\/]/g, ''));
ngModel.$render();
});
el[0].addEventListener('blur', function () {
el[0].type = 'text';
scope.$evalAsync(function () {
patternFind = new RegExp(attrs.patternFind);
var formatado = (ngModel.$viewValue || '')
.replace(patternFind, attrs.patternReplace);
ngModel.$setViewValue(formatado);
ngModel.$render();
});
});
el[0].addEventListener('keyup', function () {
if (attrs.triggerLength <= ngModel.$viewValue.length) {
el[0].blur();
}
});
}
}
});
div{ padding:20px; }
input{ padding:6px 10px; font-size:20px; width:300px; }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment