Created
October 29, 2014 19:22
-
-
Save vinicius33/5a354124e7bdcd11cca3 to your computer and use it in GitHub Desktop.
phone brazil directive
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.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