有一个字符串表达式{{zipcode}}
显示5或9位数字。
自动以xxxxx
或xxxxx-xxxx
格式显示此邮政编码的最佳方法是什么?
我相信使用过滤器是必经之路,但与过滤器和ui-mask有点混淆。
谢谢。
最佳答案
解决方案的确是使用过滤器。这是两个解决方案:
使用模块
您可以在项目中添加angular-zipcode-filter并使用以下过滤器设置邮政编码格式:{{ 981222735 | zipcode }}
自己做
此过滤器的工作原理如下:
例:
angular.module('myApp',[])
.filter('zipcode', function () {
return function (input) {
if (!input) {
return input;
}
if (input.toString().length === 9) {
return input.toString().slice(0, 5) + "-" + input.toString().slice(5);
} else if (input.toString().length === 5) {
return input.toString();
} else {
return input;
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<p>5-digit zip code: {{ 981222735 | zipcode }} </p>
<p>9-digit zip code: {{ 98122 | zipcode }} </p>
</div>