1

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?

3
  • 2
    use ng-class based on the repeat. Commented Aug 10, 2017 at 18:26
  • checkout stackoverflow.com/questions/24899699/… it has a multitude of ways to do it. I'm sure one of these ways is what you are looking for. Commented Aug 10, 2017 at 18:35
  • 1
    i think with your ng-style is good some thing like this <div ng-repeat="thing in things" ng-style="{'background-image':'url(thing.image)'}" > </div Commented Aug 10, 2017 at 18:50

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

2 Comments

but that make an img element. no background image in the div.
thats an example let me put a background image style in the div in an edit
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" />

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.