How to start Select based on an Angularjs Scope Model

Asked

Viewed 58 times

-1

I have the following code (with the listing working OK):

<select 
ng-model="elementoAtivo.tipo" 
ng-init="elementoAtivo.tipo = elementoAtivo.tipo" 
ng-options="a.valor as a.opcao for a in [{'valor':0,'opcao':'SIMPLES'},{'valor':1,'opcao':'COMPLEXO'},{'valor':2,'opcao':'TESTE'}]">
</select>

I want to initialize Option with a value that is coming in the model elementAtivo.type which is an integer between 0 and 3), but it starts the empty dropdown and when I click it shows the other options.

How do I check if the value of elementAtivo.type is the same as one of the options I put in ng-options and with that already initialize with it marked?

1 answer

0

You’re going through a list of object and your ng-model receives an integer, ie does not give "match" so that the select know what should be displayed. Hence the value entered in the variable elementAtivo.type does not reflect in select.

To reference an object by its identifier it is necessary to add the clause track by which will inform which attribute of the object will be filled by ng-model and which should be used to locate the object in the list and then display it in the <select>.

So just add track by a.valor at the end of the attribute ng-options. Your code will look (more or less) like this:

<select 
ng-model="elementoAtivo.tipo" 
ng-init="elementoAtivo.tipo = elementoAtivo.tipo" 
ng-options="a.valor as a.opcao for a in [{'valor':0,'opcao':'SIMPLES'},{'valor':1,'opcao':'COMPLEXO'},{'valor':2,'opcao':'TESTE'}] track by a.valor">
</select>

Obs:

  1. Documentation for ng-options: https://docs.angularjs.org/api/ng/directive/ngOptions

  2. I hope it’s still useful ;)

Browser other questions tagged

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