javascript - AngularJS: format the 5 or 9 digit zip-code with dash -


there string expression {{zipcode}} displays 5 or 9 digit number.

what's best way display zip-code in xxxxx or xxxxx-xxxx format automatically?

i believe using filter way go, confused filter , ui-mask.

thank you.

using filters indeed solution this. here 2 solutions:

use module

you can add angular-zipcode-filter in project , format zip code using filter:

{{ 981222735 | zipcode }}

do yourself

here how filter works:

  1. receives input
  2. verifies has 5 or 9 digits
  3. returns formatted zipcode output if has 9 digits
  4. leave in case 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.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>


Comments

Popular posts from this blog

Email notification in google apps script -

c++ - Difference between pre and post decrement in recursive function argument -

javascript - IE11 incompatibility with jQuery's 'readonly'? -