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.

Leave a Comment