Use of ng-src vs src

ghz 1years ago ⋅ 4807 views

Question

This tutorial demonstrates the use of the directive ngSrc instead of src :

<ul class="phones">
    <li ng-repeat="phone in phones" class="thumbnail">
        <img ng-src="{{phone.imageUrl}}">
    </li>
</ul>

They ask to:

Replace the ng-src directive with a plain old src attribute.
Using tools such as Firebug, or Chrome's Web Inspector, or inspecting the webserver access logs, confirm that the app is indeed making an extraneous request to /app/%7B%7Bphone.imageUrl%7D%7D (or /app/{{phone.imageUrl}} ).

I did so and it gave me the correct result:

<li class="thumbnail ng-scope" ng-repeat="phone in phones">
    <img src="img/phones/motorola-xoom.0.jpg">
</li>

Is there a reason why?


Answer

<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.