How to bind the src of an image to ng-model and extract it in Angular?

RobSeg picture RobSeg · Apr 9, 2015 · Viewed 36.3k times · Source

I want to bind the source of an image to the source of another image.

visual example

In the end result, the source of the large image should be bound to the src of the clicked smaller (thumbnail) image. Is this possible using ng-model?

Here's what I've got

        <div>
            <img ng-src="{{selectedImg.src}}">
        </div>

        <div>
            <ul ng-repeat="thumb in franchises">
                <li>
                    <img ng-src="{{thumb.images[0].list}}" ng-model="selectedImg">
                </li>
            </ul>
        </div>

Answer

Saulo Lozano picture Saulo Lozano · Apr 9, 2015

You could do it using ng-click:

<div>
    <img ng-src="{{selectedImg.src}}" alt="{{slide.images[0].list}}">
</div>

<div>
    <ul ng-repeat="thumb in franchises">
        <li>
            <img ng-src="{{thumb.images[0].list}}" 
                 alt="{{thumb.images[0].list}}" 
                 ng-click="selectedImg.src = thumb.images[0].list" />
        </li>
    </ul>
</div>

But you have to define selectedImg as an object in your controller like this:

$scope.selectedImg = {};