Search code examples
javascriptangularjsfiltercurrency

How do we customize the built in Angular "currency" filter?


I'm using Angular "currency" filter to show price in a shopping cart. The prices are fetched from a back end server. So sometimes the price may not be available to show to the user. In that case I just want to show the user that the price is not available in the same field as of currency field. I can not show plain text in a currency filter. The only solution I found is to keep another text field to show/hide when a price is not available.But this is some what unnecessary I think. Is there any way to extend or override the built in "currency" filter of Angular js ?. Kindly appreciate some help.

 <div class="large-12 medium-12 small-12 columns pad-none nzs-pro-list-item-price">
    {{item.ItmPrice|currency}}
</div>

Solution

  • Create your custom filter which will internally use currency when value is present, otherwise it will return text which you want to show instead.

    Markup

    {{amount | customFormat:"USD$": "N/A"}}
    

    Filter

    .filter('customFormat', function($filter) {
      return function(value, format, text) {
        if (angular.isDefined(value) && value != null)
          return $filter('currency')(value, format);
        else
          return text;
      }
    });
    

    Working Plunkr