Use of ng-src vs src

From Angular docs

The buggy way to write it:

<img src="http://www.gravatar.com/avatar/{{hash}}"/>

The correct way to write it:

<img ng-src="http://www.gravatar.com/avatar/{{hash}}"/>

Why? this is because on load of page, before angular bootstrapping and creation of controllers, browser will try to load image from http://www.gravatar.com/avatar/{{hash}} and it will fail. Then once angular is started, it understands that that {{hash}} has to be replaced with say logo.png, now src attribute changes to http://www.gravatar.com/avatar/logo.png and image correctly loads. Problem is that there are 2 requests going and first one failing.

TO solve this we should use ng-src which is an angular directive and angular will replace ng-src value into src attribute only after angular bootstrapping and controllers are fully loaded, and at that time {{hash}} would have already been replaced with correct scope value.


<img ng-src="{{phone.imageUrl}}"> 

This gives you expected result, because phone.imageUrl is evaluated and replaced by its value after angular is loaded.

<img src="{{phone.imageUrl}}">

But with this, the browser tries to load an image named {{phone.imageUrl}}, which results in a failed request. You can check this in the console of your browser.


The src="{{phone.imageUrl}}" is unnecessary and creates an extra request by the browser. The browser will make at least 2 GET requests attempting to load that image:

  1. before the expression is evaluated {{phone.imageUrl}}
  2. after the expression is evaluated img/phones/motorola-xoom.0.jpg

You should always use ng-src directive when dealing with Angular expressions. <img ng-src="{{phone.imageUrl}}"> gives you the expected result of a single request.


On a side note, the same applies to ng-href so you don't get broken links till the first digest cycle kicks in.