ChaseLouisPowers
ChaseLouisPowers

Reputation: 755

AngularJS ng-if generating error when used to load image

I'm getting a not found error when I load an icon using the following AngularJS HTML markup (everything works graphically though):

<div class="page-icon" ng-if="icon != null">
    <img src="{{icon}}">
</div>

Which generates the following not found error:

GET http://localhost/%7B%7Bicon%7D%7D 404 (Not Found)

Upvotes: 0

Views: 565

Answers (1)

Pedro M. Silva
Pedro M. Silva

Reputation: 1298

Use the ng-src attribute instead.

<div class="page-icon" ng-if="icon != null">
    <img ng-src="{{icon}}">
</div>

Why does this happen? Basically, because before angular even kicks in, the browser will look at the DOM and find a image with the src with a value of {{icon}}. And so it will try to load an image from http://localhost/{{icon}}. Of course, it will find none.

After AngularJs has done it's work, the src will be populated with the correct value and the image will be loaded and presented.

What ng-src does is waiting for the variable icon to have a value at least once and only then setting the value for the real attribute src. This means that only then does the browser know that is has an image to load, and it already has the correct URL.

Upvotes: 3

Related Questions