问题描述
问题一(格式化电话号码):
我有格式化在AngularJS一个电话号码,但没有过滤它。有没有办法使用过滤器或货币至10位格式化为(555)555-5255
办法?仍然preserve领域作为整数数据类型?
I'm having to format a telephone number in AngularJS but there is no filter for it. Is there a way to use filter or currency to format 10 digits to (555) 555-5255
? and still preserve the data type of the field as integer?
问题二(遮蔽信用卡号码):
我有一个映射到AngularJS信用卡领域,如:
I have a credit card field that is mapped to AngularJS, like:
<input type="text" ng-model="customer.creditCardNumber">
这是返回整数( 4111111111111111
)。我会喜欢用xxx第12位,只显示最后4我就在想如何使用过滤器,以掩盖它:此限制,但我不清楚如何。有任何想法吗?有没有办法也格式化破折号数量,但仍保留数据类型为整数?诸如此类的 4111-1111-1111-1111
。
which is returning the whole number (4111111111111111
). I will like to mask it with xxx the first 12 digits and only show the last 4. I was thinking on using filter: limit for this but am not clear as how. Any ideas? Is there a way to also format the number with dashes but still retain the data type as integer? sort of 4111-1111-1111-1111
.
推荐答案
另外,如果你只需要在格式化输出的电话号码,你可以使用这样一个自定义过滤器:
Also, if you need to format telephone number on output only, you can use a custom filter like this one:
angular.module('ng').filter('tel', function () {
return function (tel) {
if (!tel) { return ''; }
var value = tel.toString().trim().replace(/^\+/, '');
if (value.match(/[^0-9]/)) {
return tel;
}
var country, city, number;
switch (value.length) {
case 10: // +1PPP####### -> C (PPP) ###-####
country = 1;
city = value.slice(0, 3);
number = value.slice(3);
break;
case 11: // +CPPP####### -> CCC (PP) ###-####
country = value[0];
city = value.slice(1, 4);
number = value.slice(4);
break;
case 12: // +CCCPP####### -> CCC (PP) ###-####
country = value.slice(0, 3);
city = value.slice(3, 5);
number = value.slice(5);
break;
default:
return tel;
}
if (country == 1) {
country = "";
}
number = number.slice(0, 3) + '-' + number.slice(3);
return (country + " (" + city + ") " + number).trim();
};
});
然后你就可以在你的模板中使用此过滤器:
Then you can use this filter in your template:
{{ phoneNumber | tel }}
<span ng-bind="phoneNumber | tel"></span>
这篇关于在AngularJS格式电话和信用卡号码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!