Skip to content

Instantly share code, notes, and snippets.

@vinicius33
Created October 29, 2014 19:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vinicius33/5a354124e7bdcd11cca3 to your computer and use it in GitHub Desktop.
Save vinicius33/5a354124e7bdcd11cca3 to your computer and use it in GitHub Desktop.
phone brazil directive
.directive('phoneBrazil', [function(){
return {
restrict: 'A',
require: 'ngModel',
transclude: true,
link: function($scope, iElm, iAttrs, ngModel) {
if(!ngModel) return;
ngModel.$formatters.unshift(formatter);
ngModel.$parsers.unshift(parser);
iElm.on('change', function (e) {
e.target.value = formatter(ngModel.$viewValue);
});
function parser (value) {
if(!value) return;
return ngModel.$modelValue;
}
function formatter (value) {
if(!value) return;
return formatNumber(value);
}
function formatNumber(value) {
var str = value + '';
str = str.replace(/\D/g,'');
((str.length === 11) &&
(str = str.replace(/^(\d{2})(\d{5})(\d{4})/,'($1) $2-$3'))) ||
(str = str.replace(/^(\d{2})(\d{4})(\d{4})/,'($1) $2-$3'));
return str;
}
}
};
}])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment