AngularJs solve broken image on failing to load image from dynamic URL

This article will help you to deal with broken images in AngularJs apps when you load images from dynamic URL.

If you have developed web application before , there must be situations where you had to deal with broken images , you must have searched for a solution in the Stack-overflow for the same.

broken-image

The most common solution you find will be some thing like the JavaScript code below which can be found in the following thread in StackOverflow

<img src="image.png" onError="this.onerror=null;this.src='/images/default-image.png';" />

But this solution can only be used when you are loading images from the project static URL. But in AngularJs sometimes you may have to bind URL to some property or interpolate the same.

<img ng-src="{{url}}" onError="this.onerror=null;this.src='/images/default-image.png';" />


Best Solution

The best solution to handle the same is to create a onError directive so that you can reuse the same in multiple places

Javascript Code

app.directive('onError', function() {  
  return {
    restrict:'A',
    link: function(scope, element, attr) {
      element.on('error', function() {
        element.attr('src', attr.onError);
      })
    }
  }
})


Html code

In the html code you can use the angular directive to specify the default image.

<img ng-src="{{url}}" on-error="/images/default-image.png" />

You can see that the broken image is replaced with default image.

fixed-broken-image