8

I have an image element that is getting its path from an attribute I have on my angular object. However if this (imagePath) is empty I get a broken image. I would like to not render the image if the attribute is empty however I do not see a way to do this. Any ideas?

<img width="50px" src="/resources/img/products/{{current.manufacturerImage.imagePath}}">
zmanc
  • 5,201
  • 12
  • 45
  • 90

3 Answers3

21

You want to check out ngHide directive.

So your code would look something like.

<img width="50px" ng-hide="current.manufacturerImage.imagePath == ''" 
src="/resources/img/products/{{current.manufacturerImage.imagePath}}">

Alternatively, you could also try the suggestion by darkporter

<img width="50px" ng-show="current.manufacturerImage.imagePath" 
src="/resources/img/products/{{current.manufacturerImage.imagePath}}">

You could also update this to check if the object is null or undefined then hide the element.

Hinek
  • 9,519
  • 12
  • 52
  • 74
Tim B James
  • 20,084
  • 4
  • 73
  • 103
  • 9
    Pretty sure ng-hide/show don't need proper booleans and can use truthiness. I'd do `ng-show="current.manufacturerImage.imagePath"` – jpsimons Apr 26 '13 at 05:36
  • 1
    @darkporter, be careful with this approach with any value that can be 0 though, like an ID, as this could be parsed incorrectly as falsy. – adamdport May 14 '14 at 18:57
1

Alternatively ngIf directive can be used as below:

<img width="50px" *ngIf="current.manufacturerImage.imagePath !== ''" 
src="/resources/img/products/{{current.manufacturerImage.imagePath}}">
Nafeez Quraishi
  • 5,380
  • 2
  • 27
  • 34
0

This suggestion wouldn't work for me because I was generating my image links based on a users role. The user had a role, but that didn't mean they had an image associated with it.

So I created a directive:

angular.module('hideEmptyImages', [])
.directive('hideEmptyImage',function() {
    return {
        Restrict: 'AE',
        Link: function (scope, elem, attrs) {
            elem.error(function() {
                elem.hide();
            });
        }
    };
});

So:

<img hide-empty-image width="50px" src="/resources/img/products/{{current.manufacturerImage.imagePath}}">

will not show if the .imagePath is empty or if there simply isn't an associated image.

Tj Gienger
  • 1,395
  • 1
  • 12
  • 17