How to display placeholders in AngularJS for undefined expression values?

JavascriptAngularjsPlaceholder

Javascript Problem Overview


If I have an expression {{ x }} and x is undefined or null, then how can I display a placeholder for it?

I provided one solution in my answer, but I would like to know what other ways there are. Maybe, also for placeholder for promises.

Javascript Solutions


Solution 1 - Javascript

{{ counter || '?'}}. Just pure javascript. || can be used as default value. Since it would be different empty messages in each, a generalized directive would not be suitable for many cases.

If you want to apply a different class to empty ones, that's also built-in:

<div ng-class="{empty: !counter}" ng-bind="counter || ?"></div>

Solution 2 - Javascript

I would do it like this, but maybe there is a better way:

angular.module('app').filter('placeholdEmpty', function(){
  return function(input){
    if(!(input == undefined || input == null)){
      return input;
    } else {
      return "placeholder";
    }
  }
});

and then use {{ x | placeholdEmpty}}

Solution 3 - Javascript

I do it with ng-show, like this:

<strong>{{username}}</strong>
<span class="empty" ng-show="!username">N/A</span>

Sure, it adds a lot more elements to my view that I might be able to handle differently. I like though how easy it is to clearly see where my placeholder/empty values are, and I can style them differently as well.

Solution 4 - Javascript

Implement default filter:

app.filter('default', function(){
  return function(value, def) {
    return (value === undefined || value === null? def : value);
  };
});

And use it as:

{{ x | default: '?' }}

The advantage of the filter solution over {{ x || '?'}} is that you can distinguish between undefined, null or 0.

Solution 5 - Javascript

Implementing default-ish filters works, but if you're using only numbers you can use angular's own number filter

> If the input is null or undefined, it will just be returned. If the > input is infinite (Infinity or -Infinity), the Infinity symbol '∞' or > '-∞' is returned, respectively. If the input is not a number an empty > string is returned.

{{ (val | number ) || "Number not provided"}}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJustGoschaView Question on Stackoverflow
Solution 1 - JavascriptUmur KontacıView Answer on Stackoverflow
Solution 2 - JavascriptJustGoschaView Answer on Stackoverflow
Solution 3 - JavascriptjszobodyView Answer on Stackoverflow
Solution 4 - JavascriptnaXa stands with UkraineView Answer on Stackoverflow
Solution 5 - JavascriptrastasheepView Answer on Stackoverflow