如果加载的 ng 样式图像无效 url,则背景默认图像 [英] background default image if ng-style image loaded is invalid url

查看:31
本文介绍了如果加载的 ng 样式图像无效 url,则背景默认图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在像这样向我的 div 添加背景图像

I am adding background images to my div like this

ng-style="{'background-image' : 'url('+ myvariable.for.image +')'}">

其中 myvariable.for.image 是/examplesite/image/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.

推荐答案

代替 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.

像这样使用:

Used like this:

演示小提琴

这篇关于如果加载的 ng 样式图像无效 url,则背景默认图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆