Bazinga777
Bazinga777

Reputation: 5281

Setting selected item using ng-options not working

I have the following array that I am using to populate a select dropdown using ng-options but i am not able to set the selected option when the dropdown shows up.

Here is the array of data

{
                        'vehicle_year_id': 12,
                        'vehicle_color_id': 522,
                        'start_date': 'Thu Mar 26 2015 01:22:48 GMT+0000 (UTC)',
                        'end_date': 'Mon Sep 15 2014 14:37:15 GMT+0000 (UTC)',
                        'meta': {
                            'colors': [{ 'id': 522, 'caption': 'Green' }, { 'id': 523, 'caption': 'Blue' }],
                            'years': [{ 'id': 12, 'year': 2015 }, { 'id': 13, 'year': 2016 }]
                        },
                        'quantity': 8,
                        'duration': 10
                    },

and the partial code

 <select ng-model="details.vehicle_color_id" ng-init="details.vehicle_color_id || details.meta.colors[0].id" class="form-control" ng-options= "color.id as color.caption for color in details.meta.colors track by color.id">                              
                      </select>  

I can see the list of data in the dropdown list but the selected field doesn't show up at all. What is the proper way to use the option ?

Update:

I just made the following changes

 <select ng-model="details.vehicle_color_id" ng-init="details.vehicle_color_id=(details.vehicle_color_id || details.meta.colors[0].id)" class="form-control" ng-options= "color.id as color.caption for color in details.meta.colors" ng-change="getValue($index)">                              
                          </select>

and used the getValue() to check the value of the model and it was showing the correct data and also the default value is being selected. I'm curious as to why it's happening this way.

Upvotes: 0

Views: 201

Answers (1)

Pankaj Parkar
Pankaj Parkar

Reputation: 136144

Your ng-init should set value of ng-model scope variable

Markup

<select ng-model="details.vehicle_color_id" 
  ng-init="details.vehicle_color_id=(details.vehicle_color_id || details.meta.colors[0].id)"
  class="form-control" 
  ng-options="color.id as color.caption for color in details.meta.colors" 
  ng-change="getValue($index)">
</select>

Working Plunkr

Upvotes: 0

Related Questions