Angularjs ng-options: Use object property as value instead of array index

Asked

Viewed 5,761 times

2

In the code below, Angularjs ng-options renders the value but records the position in the array and not the value.

I get the following json:

[{"iduniforme":1,
  "nomeuniforme":"Uniforme 5 itens",
  "itensuniforme":[{...},{...},{...},{...},{...}]},
 {"iduniforme":2,
  "nomeuniforme":"Uniforme 7 itens",
  "itensuniforme":{...},{...},{...},{...},{...},{...},{...}]}]

Using ng-options from Angularjs, I mount my select:

<div class="form-group">
   <label>Uniforme da Equipe</label>
   <select class="form-control" name="uniforme" id="uniforme"
   ng-model="uniforme" ng-options="x.nomeuniforme for x in listaUniformes">
   <option value="">Selecione o uniforme</option>
   </select>
</div>

I can render normally, that is the options appear correctly, but when I submit the form the registered value is the position inside the array [0] or [1] and not the value in "uniform" that in this case would be "uniform 5 items" or "uniform 7 items".

How do I fix this? I need to register the value "Uniform 5 items" or "Uniform 7 items" in the base.

2 answers

2


0

Include the AS clause to help Angularjs determine the value/text pair to be used. In your case, replace

<select class="form-control" name="uniforme" id="uniforme"
   ng-model="uniforme" ng-options="x.nomeuniforme for x in listaUniformes">

for

<select class="form-control" name="uniforme" id="uniforme"
   ng-model="uniforme" ng-options="x.iduniforme as x.nomeuniforme for x in listaUniformes">

if you want to reference the property IdUniforme, or

<select class="form-control" name="uniforme" id="uniforme"
   ng-model="uniforme" ng-options="x.nomeuniforme as x.nomeuniforme for x in listaUniformes">

if you want to reference the property nomeuniforme.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.