Skip to content

Instantly share code, notes, and snippets.

@nodtem66
Forked from aberke/gist:042eef0f37dba1138f9e
Last active October 2, 2015 16:08
Show Gist options
  • Save nodtem66/f32a04e22601d0c6b75f to your computer and use it in GitHub Desktop.
Save nodtem66/f32a04e22601d0c6b75f to your computer and use it in GitHub Desktop.
a modified version from `aberke` AngularJS module for phonenumber inputs - Includes custom directive that formats telephone number input values.
/***************************************************
----------------------------------------------------
Author: Alexandra Berke (aberke)
Written: Summer 2014
----------------------------------------------------
Author: Jirawat I. (nodtem66)
Rewritten: Winter 2015
----------------------------------------------------
Formats the phonenumber as (222) 333-4444 within the input element
Binds only the number 2223334444 to the model
Can use either the directive.
INTENDED USE
Example:
--------
<input type="tel" ng-model="data.phone" phone />
Attach to your main AngularJS app edit this line:
----------------------------------
var app = angular.module('***Edit this***');
Does not handle country codes that are not '1' (USA)
****************************************************/
var app = angular.module('YourApp');
app.directive('phone', function () {
return {
require: 'ngModel',
link: function (scope, element, attrs, ngModel) {
var temp;
var formatter = function(number) {
if (!number) {return '';}
number = String(number).replace(/[^0-9\+]+/g, '');
var formattedNumber = number;
var c = (number[0] == 1) ? '1 ' : '';
number = (number[0] == 1) ? number.slice(1) : number;
// # (###) ###-####
// c (area) front-end
var area = number.substr(0,3);
var front = number.substr(3,3);
var end = number.substr(6,4);
var other = number.substr(10);
if (area) {
formattedNumber = c + " (" + area + ")"
}
if (front) {
formattedNumber += (" " + front);
}
if (end) {
formattedNumber += ("-" + end);
}
if (other) {
formattedNumber += (" " + other);
}
if (temp != formattedNumber) {
temp = formattedNumber;
ngModel.$setViewValue(formattedNumber);
ngModel.$render();
}
return formattedNumber;
};
ngModel.$parsers.push(formatter);
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment