【问题标题】:AngularJS: format the 5 or 9 digit zip-code with dashAngularJS:用破折号格式化 5 或 9 位邮政编码
【发布时间】:2015-07-26 08:23:41
【问题描述】:

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

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

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

谢谢。

【问题讨论】:

    标签: javascript html angularjs filter format


    【解决方案1】:

    使用过滤器确实是解决这个问题的方法。这里有两个解决方案:

    使用模块

    您可以在项目中添加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;
          }
        };
      });
    <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>

    【讨论】:

      猜你喜欢
      • 2013-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-26
      相关资源
      最近更新 更多