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.
| <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> |
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.
| 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; } |