admin管理员组

文章数量:1432196

There is a string expression {{zipcode}} that displays 5 or 9 digit number.

What's the best way to display this zip-code in xxxxx or xxxxx-xxxx format automatically?

I believe using filter is the way to go, but slightly confused with filter and ui-mask.

Thank you.

There is a string expression {{zipcode}} that displays 5 or 9 digit number.

What's the best way to display this zip-code in xxxxx or xxxxx-xxxx format automatically?

I believe using filter is the way to go, but slightly confused with filter and ui-mask.

Thank you.

Share Improve this question asked May 14, 2015 at 16:11 HaradzieniecHaradzieniec 9,34633 gold badges122 silver badges227 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 5

Using filters is indeed the solution for this. Here are two solutions:

Use a module

You can add angular-zipcode-filter in your project and format zip code using this filter:

{{ 981222735 | zipcode }}

Do it yourself

Here is how this filter works:

  1. Receives an input
  2. Verifies that it has 5 or 9 digits
  3. Returns a formatted zipcode output if it has 9 digits
  4. Leave it as is in case it has 5 digits

Example:

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./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>

本文标签: javascriptAngularJS format the 5 or 9 digit zipcode with dashStack Overflow