1

Update: Solved! Please see my answer below.

I am trying to display a different image with each select option in Angular. As a user clicks on each option in a menu, a different image appears next to the menu. All of this is before the form is submitted. Basically trying to do what is done here in this fiddle, but in Angular: http://jsfiddle.net/treyh/xf2pq/

html:

Current image: {{myCar.url}}
<br>
<select ng-model="myCar" class="form-control">
    <option value="">Choose a car...</option>
    <option ng-repeat="car in cars" value="{{car}}" data-image = "{{car.url}}">{{car.label}}</option>
</select>

in the js file, inside the controller:

$scope.cars = [
    {url: 'Volvo.png', label: 'Volvo'}, 
    {url: 'Benz.png', label: 'Benz'}, 
    {url: 'JohnDeer.png', label: 'John Deer'}, 
    {url: 'BMW.png', label: 'BMW'}, 
];
OneMoreQuestion
  • 1,693
  • 3
  • 25
  • 51

2 Answers2

1

I have figured out how to do this using ng-repeat and $Scope.

in the js file, inside the controller:

$scope.cars = ['Volvo', 'Benz', 'Toyota'];

$scope.myCar = "";

var carURL = {
     Volvo: 'volvo.png',
     Benz: 'benz.png',
     Toyota: 'toyota.png'
};

$scope.getCarURL = function(brand) {
     return carURL[brand];
}

and in the html:

<select ng-model="myCar">
    <option ng-repeat="car in cars" value="{{car}}">{{car}}</option>
</select>

<img ng-src="{{getCarUrl(myCar)}}">
OneMoreQuestion
  • 1,693
  • 3
  • 25
  • 51
0

Select inputs in Angular are a bit confusing at first, but here is one way to set it up.

angular
    .module('app',[])
    .controller('AppCtrl',AppCtrl);


function AppCtrl() {
    var vm = this;

    vm.car_image = null;
    vm.cars = [
        {
            'url':'audi.jpg',
            'name':'Audi'
        },
        {
            'url':'bmw.jpg',
            'name':'BMW'
        }
    ]
}

<div ng-controller="AppCtrl as ctrl">
  <select ng-model="ctrl.car_image" ng-options="c.url as c.name for c in ctrl.cars" class="form-control"></select>
  <hr>
  <img ng-src="images/{{ctrl.car_image}}" ng-show="ctrl.car_image">
</div>

Using ng-src will prevent a 404 error initially when the page loads. So when you select the option you need, the ng-model from the select input is applied to the image tag.

Rob
  • 1,840
  • 2
  • 12
  • 19