Awais Qarni Awais Qarni - 1 year ago 291
HTML Question

Show Image Element only if image exists in Angular

I have two sibling elements. One is image and other is a div. I want to show image element if image exists and show div element if image doesn't exist. My elements looks like

<img ng-show="product.img" ng-src="{{product.img}}" />
<div class="left margin-right-1 line-height-15" ng-hide="product.img">{{product.img}}</div>

results in something like
. As this is a string so
will always be true and image tag will be shown. So if image doesn't exist it will show as broken image. So basically what I want is if image doesn't exist, image tag hides and div is shown and vice versa.

I have tried a javascript function like

$scope.imageExists = function(src) {
var image = new Image();
image.src = src;
if (image.width == 0) {
return false;
} else {
return true;

And changed my image tag like

<img ng-show="product.img" ng-src="{{imageExists(product.img)}}" />

But this is very expensive. I have 100 products per page and when it loops through all images, the page becomes very very slow.

So can any body guide me what is the best way in angular to show and hide image element if image exists or not.

Answer Source

Use onError event in the image to disable the variable that is used in ng-show

<img ng-show="product.img" ng-src="{{product.img}}" onError="angular.element(this).scope().product.img = false"/>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download