Search code examples
javascriptangularjssvghrefsrc

Make img src changeable by a variable


Adding an svg image using an img tag:

<img src="/photo1.svg" width="15" height="15">

I want src to be set based on a value. In this case, having an ng-repeat:

<div ng-repeat="item in parent.items"
    <img src="/files/photo1.svg" width="15" height="15"> 
</div>

Knowing that item has another attribute, item.photo which has as value a link: /files/photo1.svg, /files/photo2.svg or /files/photo3.svg.

My question is if it's possible inside the ng-repeat to make the src change it's value based on item.photo.

It seems that giving a variable to src is not working:

<img src=item.photo width="15" height="15"> 

I tried also with ternary but did not work:

<div ng-repeat="item in parent.items"
    <img src="item.photo === '/files/photo1.svg' ? '/files/photo1.svg' : 
              item.photo === '/files/photo2.svg' ? '/files/photo2.svg' :
              '/files/photo2.svg' " width="15" height="15"> 
</div>

Solution

  • You need to use ng-src

    <div ng-repeat="item in parent.items"
        <img ng-src="{{item.photo === '/files/photo1.svg' ? '/files/photo1.svg' : 
                  item.photo === '/files/photo2.svg' ? '/files/photo2.svg' :
                  '/files/photo2.svg'}}" width="15" height="15"> 
    </div>
    

    If you want to assign value of item.photo directly to src then you can simply do like this:

    <img ng-src="{{item.photo}}" />