我创建了一个AngularJS模块,使用自定义指令和随附的过滤器为我自己处理有关电话号码的问题。
jsfiddle示例:http://jsfiddle.net/aberke/s0xpkgmq/
过滤器使用示例:
<p>{{ phonenumberValue | phonenumber }}</p>
过滤器代码:
.filter('phonenumber', function() {
return function (number) {
if (!number) { return ''; }
number = String(number);
var formattedNumber = number;
var c = (number[0] == '1') ? '1 ' : '';
number = number[0] == '1' ? number.slice(1) : number;
var area = number.substring(0,3);
var front = number.substring(3, 6);
var end = number.substring(6, 10);
if (front) {
formattedNumber = (c + "(" + area + ") " + front);
}
if (end) {
formattedNumber += ("-" + end);
}
return formattedNumber;
};
});
指令使用示例:
<phonenumber-directive placeholder="'Input phonenumber here'" model='myModel.phonenumber'></phonenumber-directive>
指令代码:
.directive('phonenumberDirective', ['$filter', function($filter) {
function link(scope, element, attributes) {
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',
},
template: '<input ng-model="inputValue" type="tel" class="phonenumber" placeholder="{{phonenumberPlaceholder}}" title="Phonenumber (Format: (999) 9999-9999)">',
};
}])
带有模块的完整代码以及如何使用它:https :
//gist.github.com/aberke/042eef0f37dba1138f9e