1

So I wrote a simple directive that intercepts 404 for the images and fallback to another image when the first one fails to load.

Works quite well but I'm having problems with some urls that returns a 404 status code but still return an image in the body (Google+ for instance).

If you want to have a look the sample of code is here https://jsfiddle.net/4cjb5srh/1/

angular.module('test', [])
.directive('imgMissing', [function() {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {

            element.bind('error', function() {
                console.log('image missing');
            });
        }
    }
}]);

In this example, the Google+ image doesn't trigger the error but the linkedin image does. I tried to use jquery .error() instead of jqlite bind('error') but didn't solve the issue.

Edit: JimTheDev pointed out that it might be the same question as if a ngSrc path resolves to a 404, is there a way to fallback to a default?. Both my and this other question are to fall back on 404 however this one is specific to the case where a 404 is returned but error is not triggered (when the response-type is specified as explained below by kwan245).

Community
  • 1
  • 1
Adraen
  • 25
  • 3
  • 2
    jsfiddle you posted is not consistent with your description – ABOS May 18 '15 at 21:19
  • Apologies, here is the proper link http://jsfiddle.net/4cjb5srh/1/ – Adraen May 18 '15 at 21:33
  • possible duplicate of [if a ngSrc path resolves to a 404, is there a way to fallback to a default?](http://stackoverflow.com/questions/16310298/if-a-ngsrc-path-resolves-to-a-404-is-there-a-way-to-fallback-to-a-default) – JimTheDev May 18 '15 at 22:24

1 Answers1

0

It looks like 404 is ignored if the response is fulfilled with image as response type.

Unfortunately as this is using browser native img src which i dont think we will able to intercept in javascript.

Alternative is to do $http our self and remove img src

angular.module('test', [])
.directive('imgMissing', function($http) {
return {
    restrict: 'A',
    link: function(scope, element, attrs) {

    $http.jsonp(attrs.srcurl +"?callback=JSON_CALLBACK").success(function(res){
       element.src('data:image/jpeg;base64,' + res.data);
    }).error(function (res) {
       console.log("failed");
    });

    }
}});

In html :

Example : http://jsfiddle.net/4cjb5srh/2/

kwangsa
  • 1,701
  • 12
  • 16