Hide element if angular attribute is empty

I have an image element that gets its path from the attribute that I have on my angular object. However, if this (imagePath) is empty, I get a broken image. I would not want to display the image if the attribute is empty, but I see no way to do this. Any ideas?

<img width="50px" src="/resources/img/products/{{current.manufacturerImage.imagePath}}"> 
+7
source share
2 answers

You want to check out ngHide .

So your code will look something like this.

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

Alternatively you can also try the darkporter suggestion

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

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

+20
source

This suggestion will not work for me, because I created my links to images based on the role of users. The user had a role, but that did not mean that 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 be displayed if .imagePath is empty or if there is simply no linked image.

0
source

All Articles