Vincent
Vincent

Reputation: 6188

Angular select not working

controller

$scope.formData = {};
$scope.formData.cars = {};
$scope.formData.cars.list = [
    { id: 1, name: 'vw 2'},
    { id: 2, name: 'vw 1'}
];
$scope.formData.cars.selected = $scope.formData.cars.list[0];

html

<select id="bookingCars" class="form-control" ng-model="formData.cars.selected" ng-options="car.code as car.name for car in formData.cars.list">

Can anyone explain why this adds a 3rd blank element and why the first property (vw 2) isn't the default value?

Upvotes: 3

Views: 228

Answers (3)

dfsq
dfsq

Reputation: 193261

Try this:

ng-options="car as car.name for car in formData.cars.list"

and it should work: plunk.

You are using ngOption in form select as label for value in array. Documentation says:

select: The result of this expression will be bound to the model of the parent element. If not specified, select expression will default to value.

So it means that you want your select part to be an object, however you provided a string car.code.

Upvotes: 2

lucuma
lucuma

Reputation: 18339

If you want to use the entire object as the value the following will work:

 {{formData.cars.selected}} -      {{formData.cars.selected.id}}
 <select id="bookingCars" class="form-control" ng-model="formData.cars.selected" 
 ng-options="c.name for c in formData.cars.list">

http://plnkr.co/edit/QZtEKWeXeHC9kcuEeGNi?p=preview

Upvotes: 1

StuR
StuR

Reputation: 12218

You shouldn't use an Object to set the selected value because you are using the value "id" of your car.

So do something like this:

 $scope.formData = {};
 $scope.formData.cars = {};
 $scope.formData.cars.list = [
                        { id: 1, name: 'vw 2'},
                        { id: 2, name: 'vw 1'}
                    ];
$scope.formData.cars.selected = $scope.formData.cars.list[1].id;

<select id="bookingCars" class="form-control" ng-model="formData.cars.selected" ng-options="car.id as car.name for car in formData.cars.list">

http://jsfiddle.net/KLDEZ/2/

Upvotes: 1

Related Questions