AngularJS:使用短划线格式化5或9位数的邮政编码

Har*_*iec 2 html javascript format filter angularjs

有一个字符串表达式{{zipcode}},显示5或9位数字.

以自动格式显示此邮政编码xxxxxxxxxx-xxxx格式的最佳方式是什么?

我相信使用过滤器是可行的方法,但与过滤器和ui-mask略有混淆.

谢谢.

Fel*_*rdi 5

使用过滤器确实是解决方案.这有两个解决方案:

使用模块

您可以在项目中添加angular-zipcode-filter并使用此过滤器格式化邮政编码:

{{ 981222735 | zipcode }}

自己做

以下是此过滤器的工作原理:

  1. 收到输入
  2. 验证它有5或9位数
  3. 如果有9位数字,则返回格式化的邮政编码输出
  4. 如果它有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;
      }
    };
  });
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)