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

ID : 20400

viewed : 28

Tags : javascripttemplatesbindingangularjsdefaultjavascript

Top 5 Answer for javascript - Angularjs Template Default Value if Binding Null / Undefined (With Filter)

vote vote

100

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> 
vote vote

81

I made the following filter:

angular.module('app').filter('ifEmpty', function() {     return function(input, defaultValue) {         if (angular.isUndefined(input) || input === null || input === '') {             return defaultValue;         }          return input;     } }); 

To be used like this:

<span>{{aPrice | currency | ifEmpty:'N/A'}}</span> <span>{{aNum | number:3 | ifEmpty:0}}</span> 
vote vote

76

Just in case you want to try something else. This is what worked for me:

Based on Ternary Operator which has following structure:

condition ? value-if-true : value-if-false 

As result:

{{gallery.date?(gallery.date | date:'mediumDate'):"Various" }} 
vote vote

62

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

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

you also try:

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

52

I really liked this answer, with ngBind, your default text can just live in the element body, and then if the ngBind evaluates to something non-null/undefined, your content is replaced automatically, and everythings happy

angularjs setting default values to display before evaluation

Top 3 video Explaining javascript - Angularjs Template Default Value if Binding Null / Undefined (With Filter)

Related QUESTION?