Pergunta

So my problem is almost the same as this one: how to use ng-option to set default value of select element

I can't get the good value to be selected. I also tried many solution with ng-init etc...

But I can't figure out how to solve it.

I have this model:

var CarSchema = new Schema({
[... some stuff ...]
ville: {
    type: Schema.ObjectId,
    ref: 'City'
}
});

var CitySchema = new Schema({
 name: {
    type: String
}
});

My HTML code:

<select ng-model="car.ville" ng-options="city.name for city in cities"><option value=""/></select>
            HERE 1: {{ car.ville | json }}
            <BR>
            HERE 2 : {{cities | json}}

As as result I get:

HERE 1: { "_id": "536fee62cadf4efc08000001", "name": "Hinsdale" } 

HERE 2 : [ { "_id": "53703935cadf4ef008000000", "name": "Noumea" }, { "_id": "536fee62cadf4efc08000001", "name": "Hinsdale" }, { "_id": "536fee3ccadf4ef808000000", "name": "Bascom" } ]

So I should have the Hinsdale city selected... but no, it's on the first row (empty row).

What I am doing wrong?? I tried so many configuration but it's still not working

Add Fiddle example: jsfiddle.net/pL44W/5

So I make it almost work with this fiddle:

http://jsfiddle.net/Tyvain/UuVYL/

  • OK to save
  • OK to retrieve the good value when we arrive on the page
  • NOT OK : don't see the value when we select in the list.

To save, mongo require only the id in the ville attribute. But to be displayed I need the name attribute...

It's like i am running in circle...

Foi útil?

Solução

You expect car.ville to be bound to a city object, but your ngOptions "says" the model should be bound to a city name.

If you want to display the city name in the dropdown, but associate your model (car.ville) with the city object, change it like this:

ng-options="city as city.name for city in cities"

Additionally, in order for ngOptions to recognize the model value it needs to reference an item in the array (and not just a different object with the same properties, since the equality check is done by reference and not by value).

See, also, this short demo.


UPDATE:

If you are sure that every item in cities has a unique _id, there is a simpler alternative based on the track by feature (introduced in v1.2):

ng-options="city as city.name for city in cities track by city._id"

Now, ngOptions can associate objects in the list with the model value not necessarily by reference, but based on the _id property. (I.e. "same _id" means "same object" as far as ngOptions is concerned, so make sure your _ids are unique.)

See, also, this other short demo.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top