Search code examples
javascriptangularjsng-optionsangularjs-ng-model

AngularJS - select with track by doesn't set list object in ng-model


I've got a select:

<select name="data_source" class="form-control" ng-model="data.data_source" ng-options="c.name for c in data_sources track by c.id"></select>

Data_source objects in my data_sources array are of the form

{id:"myid", name:"mydatasourcename", ...}

On init data.data_source contains an object I retrieve from db

{id:"myid"}

Correct value is displayed in the select but in my ng-model I have my original data_source object with only the 'id' attribute. What I would have here is the object coming from the data_sources array with all its attributes (name and other). Is there a way to do so ?


Solution

  • Though on changing the drop-down your ng-model will automatically be updated with all properties. On init you can update your data_source in below manner

    data.data_source = dataFromSever
    data_sources = dataListFromServer
    //now get the matched obj of data_sources array by matching data_source.id
    //set data_source = matchedObj.. This will ensure the correct structure of model at init