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)"});
})
}
}
});