Zlatko
Zlatko

Reputation: 19569

Angular loading img src in repeater without items

I have an angular repeater (table) which includes a src element. However, my URL gets called the first time before the items are loaded, causing one 404 load like this:

http://localhost:9000/%7B%7Bitem.obj.thumbnailurl%7D%7D 404 (Not Found)

The table looks like this (simplified):

<table>
    <thead>
        <tr>
            <th>Item title</th>
            <th>Link</th>
        </tr>
    </thead>
    <tbody>
        <tr ng-repeat="item in items">
            <td>{{item.obj.itemtitle}}</td>
            <td>
                <a href="{{item.obj.landingpageurl}}">
                    <img src="{{item.obj.thumbnailurl}}"/>
                </a>
            </td>
        </tr>
    </thead>
</table>

The items array is loaded later, as a result of a search.

What happens is each time I open this view (even without page reloads, just opening other views) I get that 404 error.

Why is that happening? How can I avoid it?

Upvotes: 4

Views: 1464

Answers (3)

Khanh TO
Khanh TO

Reputation: 48972

The problem is browsers load images immediately when the tag is parsed which is before angular has a chance to replace it with dynamic value. Try ng-src to fix that. The same holds true for href, to avoid the user clicking it before Angular has a chance to replace the {{hash}} markup with its value, try ng-href

Upvotes: 2

doodeec
doodeec

Reputation: 2927

As guys here mentioned, ng-src fixes this problem. Anyway if you are changing the image source dynamically, be sure to define the default value for a better UX to show some loader image before the code defines the real image.

Upvotes: 1

lex82
lex82

Reputation: 11297

As CodeHater suggests, using ng-src will solve this issue. The problem is that the browser interprets {{item.obj.thumbnailurl}} as a real src attribute before angular has compiled the ng-repeat and its contents. This is also the reason why you get exactly one such error even though the img tag is inside a ng-repeat. When using ng-src, angular will insert the correct src attribute in your DOM the moment it compiles the ng-repeat and its contents.

Upvotes: 7

Related Questions