How to display placeholders in AngularJS for undefined expression values?

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

I presented one solution in my answer, but I would like to know what other methods exist. Perhaps also for placeholder for promises.

+59
javascript angularjs placeholder
Mar 27 '13 at 12:14
source share
5 answers

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

If you want to apply another class to empty ones, this is also built-in:

 <div ng-class="{empty: !counter}" ng-bind="counter || ?"></div> 
+90
Mar 27 '13 at 15:02
source share

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}} {{ x | placeholdEmpty}}

+25
Mar 27 '13 at 12:14
source share

I do this with ng-show, for example:

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

Of course, this adds to me a lot more elements that I could handle in different ways. I like it though, as it’s easy to clearly see where my values ​​are placeholder / empty, and I can style them differently.

+13
Mar 27 '13 at 13:24
source share

Implement default filter:

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

And use it like:

 {{ x | default: '?' }} 

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

+5
Mar 04 '16 at 3:12
source share

The default implementation of filters, but if you use only numbers, you can use angular's own numerical 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"}} 
+2
Jul 28 '16 at 22:00
source share



All Articles