1

I have a div with an image:

<div ng-if="showIt">
    <img src="{{filepath}}/{{filename}}">
    <!-- ... and a bunch other other elements -->
</div>

The thing is {{filepath}} and {{filename}} will be null if showIt is false.

However, I always see a 404 error in my console because I think Angularjs is rendering the whole DOM, and then removing the bits where ng-if evaluates to false. This means the browser will always request the non-existent images even when showIt is false.

Is there a way prevent the DOM from creating that entire div block, so that the non-existent images will never be requested by the browser?

1 Answer 1

8

Use ng-src:

<img ng-src="{{filepath}}/{{filename}}">

The 404 errors you see aren't caused by ng-if. They're caused by the fact that the browser tries to load the image before the angular expression is evaluated by Angular. ng-src only adds the src attribute to the image once the expression is evaluated, avoiding HTTP requests to {{filepath}}/{{filename}}.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.