8

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>

2 Answers 2

11

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 = {};
Sign up to request clarification or add additional context in comments.

2 Comments

This works great, thank you. The thing is when this initializes, the large image is empty and only gets filled when a small one is clicked. How do I set this initial property?
You could assign any item from the franchises array to the $scope.selectedImg.src property. For example, if you want to show the first image from franchises, you could initialize $scope.selectedImg like this: $scope.selectedImg = {src: $scope.franchises[0].images[0].list };
5

To answer your question, according to Angular Docs, you can only bind inputs, selects and textareas with ng-model, or a custom form control.

What you probably want to do is this: (which is just what Saulo Lozano did with ng-click)

https://jsfiddle.net/4fz4nx1k/2/

<img ng-src="{{thumb.images[0].list}}" ng-click="selectedImg.src = thumb.images[0].list" >

So you can't really bind an img with an ng-model that way. Besides, if you could put an ng-model inside of an ng-repeat you would get the same "model value" in all of the repeated values of the ng-repeat collection.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.