View ng-model’s JSON as the selected dropdown option

Asked

Viewed 122 times

0

Hello, I’m having doubts if that’s possible. For example, I have a dropdown with a JSON array of courses on ng-options:

<select name="curso" ng-options="curso.cursoId.sigla + ' - ' + curso.cursoId.periodo for curso in cursos" class="form-control" ng-model="disciplina.curso" required>
    <option value="">Selecione o curso</option>
</select>

When I go to edit a discipline, the ng-model disciplina.curso already has a course object, so the idea is that the course that is in this model already appears selected in the dropdown when I open the form instead of "Select a course".

Has some recourse of its own ng-options that allows me to do this? Or will it be necessary to create a function or directive? I do not have much experience with Angularjs, so I do not know how to proceed.

Thanks in advance!

  • 1

    Hello friend for it to return selected your controller needs to provide the same data for your variable course.

  • A simple way to do this would be to define your model like this: discipline.curso = courses[0].

  • Hello @Davidsilva, I managed to do this using the track by, and also published the resolution just below. Thank you!

1 answer

0


I managed to do this using the track by, that in that case the course identifiers are sigla and the periodo:

<select name="curso" ng-options="curso.cursoId.sigla + ' - ' + curso.cursoId.periodo for curso in cursos track by curso.cursoId.sigla + curso.cursoId.periodo" class="form-control" ng-model="disciplina.curso" required disabled>
    <option value="">Selecione o curso</option>
</select>

From what I read about, used the id of the object with the track by Angular uses this id as the identifier of the object in the DOM, so it can validate whether the object that is in disciplina.curso is equal to any of the objects in the list cursos, and if this is the case, the dropdown will display the object of the ng-model as selected from the list.

Browser other questions tagged

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