Search code examples
angularjsselectng-options

Problems using AngularJS ng-options with default value as single data list


I'm using AngularJS to create a single select where ng-options is a single array data:

singleArray = {1: 'PHP', 2: 'JAVA'};

I've a pre defined ng-model value for this select as this:

modelValue = { id: 2 }

So, my select is as this:

<select ng-model="modelValue.id" ng-options="value for (key,value) in singleArray track by key">
    <option value="">Select a category</option>
</select>

But, as you can see in plnkr: http://plnkr.co/edit/f4QB27cBnqL1cgHVHXMT?p=preview

The model value is not set as default, neither the select works as expected (I can't select any value, it just doesn't work)

Can someone explain why is this two behaviors are happening and what i'm doing wrong?

I've already searched around web for the exact same example (where ng-options is a single data array as this) but can't find nothing explaining my problem.

Thanks in advance and sorry for the poor english (I'm brazilian)

Cya.


Solution

  • Try this:

    1 - Encapsulate data into array of objects...

    vm.possible = [{id:1, label:'PHP'},{id:2, label:'JAVA'}];
    

    2 - Iterate array with objects properties

     <select 
     ng-model="main.current.parent_id" 
     ng-options="item.id as item.label for item in main.possible"
     >
    

    Plunker