CSS angularjs: ng-src 相当于 background-image:url(...)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13781685/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
angularjs: ng-src equivalent for background-image:url(...)
提问by Jasper Schulte
In angularjs you have the tag ng-srcwhich 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 }}
.
在 angularjs 中,您有ng-src 标签,其目的是在 angularjs 评估放置在{{
和之间的变量之前,您不会收到无效网址的错误}}
。
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.
问题是我使用了相当多的 DIV 并background-image
设置了一个 url。我这样做是因为出色的 CSS3 属性background-size
可以将图像裁剪为 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.
唯一的问题是我收到了很多错误,原因与他们创建 ng-src 标签的原因完全相同:我在 url 中有一些变量,浏览器认为该图像不存在。
I realize that there is a possibility of writing a crude {{"style='background-image:url(myVariableUrl)'"}}
, but this seems 'dirty'.
我意识到有可能写出粗略的{{"style='background-image:url(myVariableUrl)'"}}
,但这似乎“肮脏”。
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.
我已经搜索了很多,但找不到正确的方法来做到这一点。由于所有这些错误,我的应用程序变得一团糟。
回答by hooblei
This one works for me
这个对我有用
<li ng-style="{'background-image':'url(/static/'+imgURL+')'}">...</li>
回答by jaime
ngSrc
is a native directive, so it seems you want a similar directive that modifies your div's background-image
style.
ngSrc
是本机指令,因此您似乎需要一个类似的指令来修改 div 的 background-image
样式。
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/
JSFiddle 以可爱的猫为奖励:http: //jsfiddle.net/jaimem/aSjwk/1/
回答by mythz
The above answer doesn't support observable interpolation (and cost me a lot of time trying to debug). The jsFiddle linkin @BrandonTilley comment was the answer that worked for me, which I'll re-post here for preservation:
上面的答案不支持可观察的插值(并且花费了我很多时间尝试调试)。该的jsfiddle链接在@BrandonTilley意见是对我工作的答案,我将重新发布这里保存:
app.directive('backImg', function(){
return function(scope, element, attrs){
attrs.$observe('backImg', function(value) {
element.css({
'background-image': 'url(' + value +')',
'background-size' : 'cover'
});
});
};
});
Example using controller and template
使用控制器和模板的示例
Controller :
控制器 :
$scope.someID = ...;
/*
The advantage of using directive will also work inside an ng-repeat :
someID can be inside an array of ID's
*/
$scope.arrayOfIDs = [0,1,2,3];
Template :
模板 :
Use in template like so :
像这样在模板中使用:
<div back-img="img/service-sliders/{{someID}}/1.jpg"></div>
or like so :
或者像这样:
<div ng-repeat="someID in arrayOfIDs" back-img="img/service-sliders/{{someID}}/1.jpg"></div>
回答by holographic-principle
It's also possible to do something like this with ng-style
:
也可以使用以下方法执行以下操作ng-style
:
ng-style="image_path != '' && {'background-image':'url('+image_path+')'}"
which would not attempt to fetch a non-existing image.
它不会尝试获取不存在的图像。
回答by wiherek
Similar to hooblei's answer, just with interpolation:
类似于hooblei的答案,只是插值:
<li ng-style="{'background-image': 'url({{ image.source }})'}">...</li>
回答by kristok
just a matter of taste but if you prefer accessing the variable or function directly like this:
只是品味问题,但如果您更喜欢像这样直接访问变量或函数:
<div id="playlist-icon" back-img="playlist.icon">
instead of interpolating like this:
而不是这样插值:
<div id="playlist-icon" back-img="{{playlist.icon}}">
then you can define the directive a bit differently with scope.$watch
which will do $parse
on the
attribute
那么你可以用稍微不同的方式定义指令,scope.$watch
这将$parse
在属性上做
angular.module('myApp', [])
.directive('bgImage', function(){
return function(scope, element, attrs) {
scope.$watch(attrs.bgImage, function(value) {
element.css({
'background-image': 'url(' + value +')',
'background-size' : 'cover'
});
});
};
})
there is more background on this here: AngularJS : Difference between the $observe and $watch methods
这里有更多背景:AngularJS : Difference between the $observe and $watch methods
回答by Subhojit Mondal
@jaime your answer is fine. But if your page has the $http.get then you have use ng-if
@jaime 你的回答很好。但是如果你的页面有 $http.get 那么你就可以使用 ng-if
app.directive('backImg', function(){
return function($scope, $element, $attrs){
var url = $attrs.backImg;
$element.css({
'background-image': 'url(' + url + ')',
'background-size': 'cover'
});
}
});
in the factory
在工厂
app.factory('dataFactory', function($http){
var factory = {};
factory.getAboutData = function(){
return $http.get("api/about-data.json");
};
return factory;
});
in the controller area
在控制器区域
app.controller('aboutCtrl', function($scope, $http, dataFactory){
$scope.aboutData = [];
dataFactory.getAboutData().then(function(response){
// get full home data
$scope.aboutData = response.data;
// banner data
$scope.banner = {
"image": $scope.aboutData.bannerImage,
"text": $scope.aboutData.bannerText
};
});
});
and the view if you use the ng-if like below then you will get the image by interpolation otherwise, you can't get the image because directive get the value before HTTP request.
和视图,如果您使用如下所示的 ng-if,则您将通过插值获取图像,否则无法获取图像,因为指令在 HTTP 请求之前获取值。
<div class="stat-banner" ng-if="banner.image" background-image-directive="{{banner.image}}">
回答by Pat Migliaccio
I've found with 1.5 components that abstracting the styling from the DOM to work best in my async situation.
我发现有 1.5 个组件可以从 DOM 中抽象出样式,以便在我的异步情况下工作得最好。
Example:
例子:
<div ng-style="{ 'background': $ctrl.backgroundUrl }"></div>
And in the controller, something likes this:
在控制器中,是这样的:
this.$onChanges = onChanges;
function onChanges(changes) {
if (changes.value.currentValue){
$ctrl.backgroundUrl = setBackgroundUrl(changes.value.currentValue);
}
}
function setBackgroundUrl(value){
return 'url(' + value.imgUrl + ')';
}
回答by aralar
Since you mentioned ng-src
and it seems as though you want the page to finish rendering before loading your image, you may modify jaime's answer to run the native directive afterthe browser finishes rendering.
由于您提到ng-src
并且似乎您希望页面在加载图像之前完成渲染,您可以修改 jaime 的答案以在浏览器完成渲染后运行本机指令。
This blog postexplains this pretty well; essentially, you insert the $timeout
wrapperfor window.setTimeout
before the callback function wherein you make those modifications to the CSS.
这篇博文很好地解释了这一点;本质上,您在回调函数之前插入$timeout
包装器,您可以window.setTimeout
在其中对 CSS 进行这些修改。