Angularjs Template Default Value if Binding Null / Undefined (With Filter)

Undistraction picture Undistraction · May 13, 2013 · Viewed 168.1k times · Source

I have a template binding that displays a model attribute called 'date' which is a date, using Angular's date filter.

<span class="gallery-date">{{gallery.date | date:'mediumDate'}}</span>

So far so good. However at the moment, if there is no value in the date field, the binding displays nothing. However, I would like it to display the string 'Various' if there is no date.

I can get the basic logic using a binary operator:

<span class="gallery-date">{{gallery.date || 'Various'}}</span>

However I can't get it to work with the date filter:

<span class="gallery-date">{{gallery.date | date:'mediumDate' || "Various"}}</span>

How can I use the binary operator alongside the date filter?

Answer

Undistraction picture Undistraction · May 13, 2013

Turns out all I needed to do was wrap the left-hand side of the expression in soft brackets:

<span class="gallery-date">{{(gallery.date | date:'mediumDate') || "Various"}}</span>