p2004a p2004a - 1 year ago 140
Javascript Question

ngSrc is computed before ngIf causing unnecessary http request

When you write something like:

<img ng-if="image.name != null" ng-src="img/{{ image.name }}_img.png" />

image.name = null
Angular will first add tag and evaluate src. The browser will make http request for
wchich doesn't exists. Then angular will remove tag after parsing ngIf directive. What is the simplest way to resolve this issue? I thought that it's perfect use case for ngSrc and ngIf.


In current unstable 1.2.0-rc.2 issue is fixed and everything works how it is supposed to do. In current stable 1.0.8 you can't even use ternary operator.

Answer Source

You don't need the ng-if directive for this. Just do a ternary operator test in your expression. Something like

<img ng-src="{{image.name?('img/'+ image.name +'_img.png'):null}}"/>

and it should work. See my plunker http://plnkr.co/edit/BWiGdO?p=preview

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download