I am searching for a directive that can automatically set the background image to a specific image if it exists, or default to another image.
The url
is generated using the form /images/cards/card{{$index}}.jpg
within an ng-repeat
, however, not all images actually exist.
Currently, I have code that accomplishes this task, but it also logs failed $http
requests to the console, which is not desired as the purpose of this script is to handle non-existent images gracefully. Are there any suggestions on how to prevent these error messages from being displayed? (I have considered using the error event available in an <img>
tag, but cannot find evidence that background-image
has a similar feature).
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)"});
})
}
}
});