1

I want a directive that sets the background image to a specific image, if it exists, or to a default one.

url takes the form /images/cards/card{{$index}}.jpg from an ng-repeat, but only some of the images actually exist.

This does it, but the failed $http requests are being logged to the console which I don't want (as the whole point of this code is to be aware that some images don't exist). Any advice? (It seems that an<img> tag has an error event that can be trapped, but I can't find evidence background-image has one too.

angular.module("stickers")
.directive('bkgDiv', function($http) {
    return {
        scope: {
            url: '@'
        },
        link: function(scope, elem, attrs) {
            // console.log("bkgDiv", scope.url);
            $http.get(scope.url)
            .success(function() {
                elem.css({backgroundImage: "url("+scope.url+")"});
            })
            .error(function() {
                elem.css({backgroundImage: "url(/images/animal.png)"});
            })
        }
    }
});
Moppo
  • 18,797
  • 5
  • 65
  • 64
Simon H
  • 20,332
  • 14
  • 71
  • 128
  • I'd tell you to make sure `scope.url` is not null, but I don't know your code. Is there a possibility `scope.url` will not be null and not point to a valid image url? – Moti Azu Aug 02 '15 at 12:31
  • @MotiAzu indeed, `scope.url` will often not point to a valid url - have updated question – Simon H Aug 02 '15 at 12:34
  • 1
    Perhaps this will work ? http://stackoverflow.com/questions/21073026/catch-errors-with-window-onerror-yet-see-errors-on-console – Omri Aharon Aug 02 '15 at 12:35
  • See http://stackoverflow.com/questions/16192464/window-onerror-not-working-in-chrome – Wédney Yuri Aug 02 '15 at 12:41
  • According to this http://stackoverflow.com/questions/22113286/prevent-http-errors-from-being-logged-in-browser-console window.error might be the only way. – Moti Azu Aug 02 '15 at 12:42

1 Answers1

0

In your controller you'd establish another field at the same level as the image url and you'd test for its existence then, storing result in a Boolean (as far as JS does Booleans). That way you can bind to this new Boolean in your view.

S Meaden
  • 8,050
  • 3
  • 34
  • 65