Selects selected from object

Asked

Viewed 169 times

0

Inputs of type select are not selected when loading a form from an object. The values of select are set in the controller. How do I load the page and select them with the object values?

For example, if the project type value is 2, select comes with the option with value 2.

HTML:

<select class="form-control" name="tipo" ng-model="vm.projeto.tipo" ng-options="k as v for (k, v) in vm.tipos">
    <option value="">Selecione o tipo projeto</option>
</select>

Ctrl:

vm.projeto = {
    nome: "Projeto 1",
    tipo: 2
};

vm.tipos = {
    1: "Tipo 1", 
    2: "Tipo 2", 
    3: "Tipo 3"
};

EDIT: In this post: How to set a value in select that is mounted with ng-options, the solution was to use a string type value instead of number, but I did the test and it did not work, the curious thing is that so it seems to change the option and back to the default very fast.

2 answers

1

You will have to use one of the iteration modes up the object and produce each option hence.

You can use the ng-repeat or the ng-options. I prefer the ng-options because we do not have to interpolate our output since the directive deals with it.

Without changing its code structure, it’s also possible to do what you want;

  <select name="selected" id="selected" ng-model="selecionado_2">
    <option ng-repeat="(tipo, nome) in tipos track by $index" value="{{tipo}}">{{nome}}</option>
  </select>
  Selecionado: {{::selecionado_2}}

Organizing your code and using ng-options

function Types($scope) {

  $scope.selecionado = {};
  $scope.types = [
    { valor: 1, nome: "Tipo 1"},
    { valor: 2, nome: "Tipo 2"},
    { valor: 3, nome: "Tipo 3"},
    { valor: 4, nome: "Tipo 4"},
    { valor: 5, nome: "Tipo 5"}
  ]
}

angular.module('app', [])
  .controller('Types', Types);

angular.bootstrap(document.body, ['app']);

<body ng-controller="Types">

  <select name="selected" id="selected" ng-model="selecionado" 
          ng-options="type.nome for type in types track by type.valor">
    <option value="">---Seleciona um Tipo---</option>
  </select>
  Selecionado: {{selecionado}}
</body>

Basically, we use the directive ng-options to iterate up our object types containing the type value and type name.

Here’s the Jsfiddle

0


I decided to change the ng-options and the list vm.tipos. Stayed like this:

HTML:

<select class="form-control" name="tipo" ng-model="vm.projeto.tipo" ng-options="tipo.valor as tipo.descricao for tipo in vm.tipos">
    <option value="">Selecione o tipo projeto</option>
</select>

Ctrl:

vm.projeto = {
    nome: "Projeto 1",
    tipo: 2
};

vm.tipos = [
  {valor: 1, descricao: "Tipo 1"},
  {valor: 2, descricao: "Tipo 2"},
  {valor: 3, descricao: "Tipo 3"}
];

Now all the selects already comes with the option selected according to the objeto of ng-model

Browser other questions tagged

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