Awais Qarni Awais Qarni - 7 months ago 138
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>


And
product.img
results in something like
/assets/images/prod.jpg
. As this is a string so
ng-show
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

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"/>