AngularJS:用破折号格式化 5 或 9 位邮政编码
AngularJS: format the 5 or 9 digit zip-code with dash
有一个字符串表达式 {{zipcode}}
显示 5 或 9 位数字。
自动以 xxxxx
或 xxxxx-xxxx
格式显示此邮政编码的最佳方式是什么?
我认为使用过滤器是可行的方法,但与过滤器和 ui-mask 有点混淆。
谢谢。
使用过滤器确实是解决这个问题的方法。这里有两个解决方案:
使用模块
您可以在您的项目中添加 angular-zipcode-filter 并使用此过滤器格式化邮政编码:
{{ 981222735 | zipcode }}
自己动手
此过滤器的工作原理如下:
- 收到输入
- 验证它有 5 位还是 9 位数字
- Returns 如果有 9 位数字则输出格式化的邮政编码
- 保持原样,以防它有 5 个数字
示例:
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>
有一个字符串表达式 {{zipcode}}
显示 5 或 9 位数字。
自动以 xxxxx
或 xxxxx-xxxx
格式显示此邮政编码的最佳方式是什么?
我认为使用过滤器是可行的方法,但与过滤器和 ui-mask 有点混淆。
谢谢。
使用过滤器确实是解决这个问题的方法。这里有两个解决方案:
使用模块
您可以在您的项目中添加 angular-zipcode-filter 并使用此过滤器格式化邮政编码:
{{ 981222735 | zipcode }}
自己动手
此过滤器的工作原理如下:
- 收到输入
- 验证它有 5 位还是 9 位数字
- Returns 如果有 9 位数字则输出格式化的邮政编码
- 保持原样,以防它有 5 个数字
示例:
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>