viana
viana

Reputation: 515

Define a default image if the variable {{image}} is empty

My <img>:

<img width="90" height="90"  src="{{image}}" />

Default image folder: assets/img/pic_user.png

How can I define a default image that is not defined in the variable: {{image}} ?

Upvotes: 2

Views: 7246

Answers (4)

Stefan Svrkota
Stefan Svrkota

Reputation: 50633

You can store default image route in variable and then use ternary operator to use it in case image doesn't exist:

defaultImage: string = "assets/img/pic_user.png";

And then in your template:

<img width="90" height="90"  [src]="image ? image : defaultImage" />

Notice that I used property binding instead of interpolation, it is much more elegant in my opinion.

Upvotes: 7

uzr
uzr

Reputation: 1220

Use a fallback image

<img fallback-src="fallbackimg" ng-src="{{image}}"/>

myApp.directive('fallbackSrc', function () {
  var fallbackSrc = {
    link: function postLink(scope, iElement, iAttrs) {
      iElement.bind('error', function() {
        angular.element(this).attr("src", iAttrs.fallbackSrc);
      });
    }
   }
   return fallbackSrc;
});

from: Angular directive for a fallback image

Upvotes: 0

A. Kutluozen
A. Kutluozen

Reputation: 96

There is a trick to set default values in JavaScript:

var a = newValue || 0;

Same also works for Angular. In your case:

<img width="90" height="90" src="{{image || 'assets/img/pic_user.png' }}" />

Upvotes: 1

Avinash Raj
Avinash Raj

Reputation: 174706

Use Logical OR operator ||

<img width="90" height="90"  src="{{image||'assets/img/pic_user.png'}}" />

Upvotes: 8

Related Questions