Eddie
Eddie

Reputation: 1

AngularJS: Preselecting multiple options in listbox

My markup looks like this:

<select multiple="multiple" size="7" 
     ng-model="model.SelectedCars" 
     ng-options="car.Code as car.Name for car in model.Cars track by car.Code">
</select>

I have initialized my scope with the following:

$scope.model.SelectedCars = [];
$scope.model.Cars = [
{Name: 'Car 1', Code: 'id01'},
{Name: 'Car 2', Code: 'id02'},
{Name: 'Car 3', Code: 'id03'}
];

This all works the way I want it to (Car name is displayed in listbox, Code is used as value). When I select something from the listbox (even multiple values), the $scope.model.SelectedCars array ends up populated with the Codes for each selected car(1d array of strings).

My question is, why if I manually push valid Codes into the $scope.model.SelectedCars array, is it not being reflected in the UI control as selected. This only happens when using ng-options or ng-repeat, seems like if I hard code the options to the it does work.

The server will only provide my selected cars model as a 1d array of Codes (strings). I would much rather keep the data structure for the ng-model as is so I can send it up without any alterations prior to posting.

Any help is appreciated!

Upvotes: 0

Views: 3608

Answers (1)

Malkus
Malkus

Reputation: 3726

This is a known issue

That being said if you remove track by from ngOptions you can add a model.Cars.code to the list of model.selectedCars and the two way binding will work.

<select multiple="multiple" size="7" 
    ng-model="model.SelectedCars" 
    ng-options="car.Code as car.Name for car in model.Cars"></select>

Upvotes: 0

Related Questions