Dynamic background image with Angular JS ng-repeat

巧了我就是萌 提交于 2019-12-24 09:39:45

问题


Id like to display dynamic background images using angular's ng-repeat directive.

At the moment Im doing this by setting it as an inline style like so:

<div ng-repeat="thing in things" 
     style="background-image: url({{thing.image}})" >
</div

I would prefer to use standard angular tools to accomplish this and avoid using inline styles. I would set a static background image using ng-style but this does not seem practical for an indeterminate number of objects.

What is the correct solution for something like this?


回答1:


To set an image dynamically, suggest to use ng-src

<div ng-repeat="thing in things">
     <img ng-src="{{thing.ImageUrl}}" />
</div

This would then give you expected result, because thing.ImageUrl is evaluated and replaced by its value after angular is loaded.

Update as a background Image now

<div ng-repeat="thing in things" ng-style="{'background-image': 'url(' + thing.ImageUrl + ')'}"></div



回答2:


you can use it into <img> tags like below

<img ng-repeat="x in array" src="{{ x.image_url }}" style="static inline stylesheet" />

or use

<img ng-repeat="x in array" ng-src="x.image_url" style="static inline stylesheet" />


来源:https://stackoverflow.com/questions/45620961/dynamic-background-image-with-angular-js-ng-repeat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!