angularjs:ng-src 等效于 background-image:url(...) [英] angularjs: ng-src equivalent for background-image:url(...)
问题描述
在 angularjs 中,你有 tag ng-src 其目的是在 angularjs 开始评估 {{
和 }}
之间的变量之前,您不会收到无效 url 的错误.
问题是我使用了相当多的 DIV,并将 background-image
设置为 url.我这样做是因为出色的 CSS3 属性 background-size
将图像裁剪为 DIV 的确切大小.
唯一的问题是我收到了很多错误,原因与他们创建 ng-src 标签的原因完全相同:我在 url 中有一些变量,而浏览器认为该图像不存在.
我意识到有可能编写一个粗略的 {{"style='background-image:url(myVariableUrl)'"}}
,但这看起来很脏".
我已经搜索了很多,但找不到正确的方法来做到这一点.由于所有这些错误,我的应用程序变得一团糟.
ngSrc
是本机指令,因此您似乎想要一个类似的指令来修改 div 的 background-image代码>风格.
您可以编写自己的指令来完全满足您的需求.例如
app.directive('backImg', function(){返回函数(范围,元素,属性){var url = attrs.backImg;元素.css({'背景图片': 'url(' + url +')',背景尺寸":封面"});};});
你会像这样调用
JSFiddle 以可爱的猫为奖励:http://jsfiddle.net/jaimem/aSjwk/1/
In angularjs you have the tag ng-src which has the purpose that you won't receive an error for an invalid url before angularjs gets to evaluate the variables placed in between {{
and }}
.
The problem is that I use quite some DIV's with a background-image
set to an url. I do this because of the excellent CSS3 property background-size
which crops the image to the exact size of the DIV.
The only problem is that I receive a lot of errors for the exact same reason they created a ng-src tag: I have some variables in the url and the browser thinks the image doesn't exist.
I realize that there is a possibility of writing a crude {{"style='background-image:url(myVariableUrl)'"}}
, but this seems 'dirty'.
I've searched a lot and can't find the right way to do this. My app is becoming a mess because of all of these errors.
解决方案 ngSrc
is a native directive, so it seems you want a similar directive that modifies your div's background-image
style.
You could write your own directive that does exactly what you want. For example
app.directive('backImg', function(){
return function(scope, element, attrs){
var url = attrs.backImg;
element.css({
'background-image': 'url(' + url +')',
'background-size' : 'cover'
});
};
});
Which you would invoke like this
<div back-img="<some-image-url>" ></div>
JSFiddle with cute cats as a bonus: http://jsfiddle.net/jaimem/aSjwk/1/
这篇关于angularjs:ng-src 等效于 background-image:url(...)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文