phonenumberModule
Formats the phonenumber as (222) 333-4444 within the input element Binds only the number 2223334444 to the model Can use either the directive or filter as stand alone items.
by zachreynolds
HTML
<div ng-app="phonenumberModule" ng-controller="MyCntl">
<p>phonenumber value: {{ myModel.phonenumber }}</p>
<p>formatted phonenumber: {{ myModel.phonenumber | phonenumber }}</p>
<phonenumber-directive placeholder="myPrompt" model='myModel.phonenumber'></phonenumber-directive>
</div>
CSS
.phonenumber {
min-width: 200px;
}
JavaScript
// see gist: https://gist.github.com/aberke/042eef0f37dba1138f9e
function MyCntl($scope) {
$scope.myModel = {};
$scope.myPrompt = "Input your phonenumber here!";
}
var phonenumberModule = angular.module('phonenumberModule', [])
.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)">',
};
}])
.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: (###) ###-####
if number.length < 4: ###
else if number.length < 7: (###) ###
Does not...