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}}">
1

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Pretty sure ng-hide/show don't need proper booleans and can use truthiness. I'd do ng-show="current.manufacturerImage.imagePath"
@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.
1

Alternatively ngIf directive can be used as below:

<img width="50px" *ngIf="current.manufacturerImage.imagePath !== ''" 
src="/resources/img/products/{{current.manufacturerImage.imagePath}}">

1 Comment

this is now the correct answer. Thank you for keeping it updated.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.