alexandremoraes
alexandremoraes

Reputation: 59

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.

Upvotes: 0

Views: 1035

Answers (2)

atrain
atrain

Reputation: 51

You don't have to wrap your object in an array to get this to work. First, use the following to set the default value:

modelValue = singleArray["2"];

To get the select to work, remove the "track by key" clause and adjust your ng-model:

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

Here's a plunker with the fix that I forked from your original: http://plnkr.co/edit/QdQ8sTQDNIcov0PiiZ8Z?p=preview

Upvotes: 0

Marcelo Aymone
Marcelo Aymone

Reputation: 293

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

Upvotes: 1

Related Questions