如果装载NG-风格形象是无效的网址背景的默认图像 [英] background default image if ng-style image loaded is invalid url
问题描述
我添加背景图片到我的div像这样
I am adding background images to my div like this
ng-style="{'background-image' : 'url('+ myvariable.for.image +')'}">
其中myvariable.for.image像/ examplesite /图像/ ID的网址
where myvariable.for.image is a url like /examplesite/image/id
这工作正常但有一个例外,如果图像是不存在的,它只是没有做任何事情,我的背景看起来太喇嘛......如果图像犯规存在我希望能够有一个默认的形象来代替它。
This works fine with one exception, if the image is not there it just doesnt do anything and my background looks too bla...If the image doesnt exist I want to be able to replace it with a default image.
但我似乎无法弄清楚如何
But I cant seem to figure out how
推荐答案
而不是 ngStyle
的我会使用一个自定义的指令这一点。如以下内容。这种检查是否提供了一个属性,如果是的话它会试图加载图像。如果它加载图像,然后我们设置背景图片,否则我们使用默认的图像。
Instead of ngStyle
I'd use a custom directive for this. Such as the following. This checks to see if an attribute is provided, if so it attempts to load that image. If it loads an image then we set the background image to it, otherwise we use a default image.
myApp.directive('bgImage', function () {
return {
link: function(scope, element, attr) {
attr.$observe('bgImage', function() {
if (!attr.bgImage) {
// No attribute specified, so use default
element.css("background-image","url("+scope.defaultImage+")");
} else {
var image = new Image();
image.src = attr.bgImage;
image.onload = function() {
//Image loaded- set the background image to it
element.css("background-image","url("+attr.bgImage+")");
};
image.onerror = function() {
//Image failed to load- use default
element.css("background-image","url("+scope.defaultImage+")");
};
}
});
}
};
});
用于这样的:
<div bg-image="{{person.src}}">
这篇关于如果装载NG-风格形象是无效的网址背景的默认图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!