I was wondering how to automatically format a number in an input field using an angularjs directive? When I type in an input field say 6042919283 I want it to be shown as 6
If your phone number is uniform i.e all the number is of digit 10 this one will work
app.directive('formatPhone', [
function() {
return {
require: 'ngModel',
restrict: 'A',
link: function(scope, elem, attrs, ctrl, ngModel) {
elem.add(phonenumber).on('keyup', function() {
var origVal = elem.val().replace(/[^\w\s]/gi, '');
if(origVal.length === 10) {
var str = origVal.replace(/(.{3})/g,"$1-");
var phone = str.slice(0, -2) + str.slice(-1);
jQuery("#phonenumber").val(phone);
}
});
}
};
}
]);
And your html;