0

I am displaying data from a large json object and want to filter the value as a currency, but only if it exists. Otherwise I want to print out a dash. The problem I am having is that the currency filter will filter the dash into nothing. Is there a way to filter on the first part of a conditional but not the second?

Want to show either the dollar amount or a dash

{{obj.dollarAmount || '-'}}

Also want to filter the dollar amount as a currency (this obviously is invalid code)

{{obj.dollarAmount | currency || '-'}}

This is not what I want because it will display an empty string when it should be showing a dash. (because currency filter on a dash returns an empty string)

{{obj.dollarAmount || '-' | currency}}
1
  • maybe make a custom filter, sounds like something you're going to reuse. Commented Sep 22, 2015 at 20:22

2 Answers 2

1

You were very close. Evaluate the value as currency first, and then apply the conditional.

{{(obj.dollarAmount | currency) || "-"}}
Sign up to request clarification or add additional context in comments.

Comments

1

You could do a ternary statement against the dollar amount like so:

{{obj.dollarAmount ? (obj.dollarAmount | currency) : '-'}}

The alternative would be to create a custom filter that looks at the amount and either applies the currency filter or returns -.

Edit

As @ergonaut mentioned, it is probably best to go with a filter for reusability. If you wanted to go that route:

.filter('myCurrency', [
  '$filter',

  function($filter) {
    return function(amount) {
      return amount ? $filter('currency')(amount) : '-';
    };
  }
]);

This is very similar to the ternary statement (and uses the same currency filter) with extra benefits. First it is reusable, you can use {{obj.dollarAmount | myCurrency}} anywhere in your application. You can also add additional validation against the amount or modify the display of the amount.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.