0

I'm trying to conditionally display an image with ng-style. I've tried all the suggestions listed here (and in the docs) but nothing seems to work.

    first try:
<br/>
<img alt="" ng-style="{'background-image':'url(\'https://www.google.com/images/srpr/logo4w.png\')'}">
<br/>
second try:    
<br/>
<img src="" alt="" ng-style="{'background-image':'url(\'https://www.google.com/images/srpr/logo4w.png\')'}">
<br/>
third try:    
<br/>
<img src="" alt="" ng-style="{background-image:'url(https://www.google.com/images/srpr/logo4w.png)'}">
<br/>
fourth try:    
<br/>
<img src="" alt="" ng-style="{background:'url(https://www.google.com/images/srpr/logo4w.png)'}">

Here's a JSFiddle

Community
  • 1
  • 1
McMeep
  • 688
  • 2
  • 8
  • 13

1 Answers1

1

The background-image doesn't make sense with the <img> element so you need to use ng-src instead of ng-style.

Also, you're missing the ng-app attribute in your example so Angular isn't actually running.

So a working example would be:

<div ng-app>
    <img ng-src="https://www.google.com/images/srpr/logo4w.png">
</div>

Although, I guess you can use ng-style on other elements, like a div. Just make sure it has content in it so the background actually shows up:

<div ng-app>
    <div style="padding: 20px;" ng-style="{'background-image':'url(\'https://www.google.com/images/srpr/logo4w.png\')'}">This is some content</div>
</div>
Sly_cardinal
  • 12,270
  • 5
  • 49
  • 50
  • What if I also need to change some style properties as well (height,width, etc)? Seems like the solution is to use a div.. – McMeep Mar 10 '14 at 08:25
  • In that case it's fine, you can use the `ng-style` tag to set those sorts of properties. It just doesn't make sense to set `background-image` on an `` element. – Sly_cardinal Mar 10 '14 at 10:24