2

I have a simple case: some objects output via ng-repeat to html page. Every object has a path to image to show. Here's the problem: even though I have an empty array of objects, it seems like the browser tries to load image with incorrect URL (I see 404 errors via firebug). Code:

<ul class="thumbnails">
  <div class="row-fluid" ng-repeat="item in searchItems" ng-if="$index%2==0">
    <div class="span5" ng-repeat="item in searchItems|limitTo:2:$index">
      <div class="thumbnail" style="border-style:none;box-shadow: 0 0 0 0;">
        <b>{{item.name}}</b><br>
        <img height="160" src="{{item.imageUrl}}" class="img-rounded"><br>
      </div><!--thumbnail-->
    </div><!--span-->
  </div>
</ul>

Error that I see in firebug:

NetworkError: 404 Not Found - http://localhost:8000/app/%7B%7Bitem.imageUrl%7D%7D

So it seems like the browser tries to load image before angularjs processes its instructions. Besides this error, everything is working well. However, I want to eliminate this problem. How can I do this?

thanksd
  • 54,176
  • 22
  • 157
  • 150
sphinks
  • 3,048
  • 8
  • 39
  • 55

1 Answers1

3

Use ng-src. It's the angular.js solution to this problem. ng-src prevents your browser from "jumping the gun", an only loads the image once the item.imageUrl's value has been properly resolved.

To quote the Angular docs on ng-src:

Using Angular markup like {{hash}} in a src attribute doesn't work right: The browser will fetch from the URL with the literal text {{hash}} until Angular replaces the expression inside {{hash}}. The ngSrc directive solves this problem.

So, your code would become:

<img height="160" ng-src="{{item.imageUrl}}" class="img-rounded"><br>
Alex Johnson
  • 1,504
  • 13
  • 20