Har*_*iec 2 html javascript format filter angularjs
有一个字符串表达式{{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;
}
};
});Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)