Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a function in <img> to define the path of the src

I'm trying to to something like that :

<img id="icon" class="cercle icon" src="getIcon({{item.status}})" alt="">

The function is :

getIcon(status){
    switch (status) {
      case 'Ongoing':
        return '../../../../assets/img/icon/PinPlot.png';
      case 'Signaled':
        return '../../../../assets/img/icon/PinWarning.png';
      case 'Finished':

      default:
        return '../../../../assets/img/icon/Pin red.png';
    }
  }

But all I get is no image like if it's not found. But no error nor warning.

Any idea ?

like image 470
An-droid Avatar asked Dec 04 '22 21:12

An-droid


2 Answers

Although the previous answer of using [src] is the way I would recommend, the reason why your existing technique doesn't work is because you're not using interpolation (i.e. {{....}} ) correctly.

You have:

<img id="icon" class="cercle icon" src="getIcon({{item.status}})" alt="">

when you probably meant:

<img id="icon" class="cercle icon" src="{{ getIcon(item.status) }}" alt="">

Explanation:

You can think of it this way. Within your template, everything outside {{ }} is treated as literal strings. It's only things within the double braces that are treated as code to execute. So, with your example, because of where you put your braces, you'd end up with the string:

src="getIcon(Ongoing)" 

after the interpolation, cuz you're only including the item.status within your braces, instead of the entire expression.

like image 38
snorkpete Avatar answered Dec 09 '22 15:12

snorkpete


Use [src]:

<img id="icon" class="cercle icon" [src]="getIcon(item.status)" alt="">

And also you dont need to getIcon({{item.status}}) but without {{}}.

like image 105
SrAxi Avatar answered Dec 09 '22 13:12

SrAxi