I created an AngularJS module to deal with this phonenumbers issue for myself using a custom directive and an accompanying filter.
Jsfiddle example: http://jsfiddle.net/aberke/s0xpkgmq/
Filter Usage Example: <p>{{ phonenumberValue | phonenumber }}</p> <p>{{ phonenumberValue | phonenumber }}</p>
Filter Code:
.filter('phonenumber', function() { /* Format phonenumber as: c (xxx) xxx-xxxx or as close as possible if phonenumber length is not 10 if c is not '1' (country code not USA), does not use country code */ return function (number) { /* @param {Number | String} number - Number that will be formatted as telephone number Returns formatted number: (
An example of using the directive:
<phonenumber-directive placeholder="'Input phonenumber here'" model='myModel.phonenumber'></phonenumber-directive>
Directive Code:
.directive('phonenumberDirective', ['$filter', function($filter) { /* Intended use: <phonenumber-directive placeholder='prompt' model='someModel.phonenumber'></phonenumber-directive> Where: someModel.phonenumber: {String} value which to bind only the numeric characters [0-9] entered ie, if user enters 617-2223333, value of 6172223333 will be bound to model prompt: {String} text to keep in placeholder when no numeric input entered */ function link(scope, element, attributes) { // scope.inputValue is the value of input element used in template scope.inputValue = scope.phonenumberModel; scope.$watch('inputValue', function(value, oldValue) { value = String(value); var number = value.replace(/[^0-9]+/g, ''); scope.phonenumberModel = number; scope.inputValue = $filter('phonenumber')(number); }); } return { link: link, restrict: 'E', scope: { phonenumberPlaceholder: '=placeholder', phonenumberModel: '=model', }, // templateUrl: '/static/phonenumberModule/template.html', template: '<input ng-model="inputValue" type="tel" class="phonenumber" placeholder="{{phonenumberPlaceholder}}" title="Phonenumber (Format: (999) 9999-9999)">', }; }])
Full code with the module and how to use it: https://gist.github.com/aberke/042eef0f37dba1138f9e
aberke Aug 13 '14 at 3:32 2014-08-13 03:32
source share