Search code examples
cssangularjsng-style

using angular ng-style on an image tag to call out a background image


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


Solution

  • 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>