Selected selects from object

0

Select inputs are not selected when I load a form from an object. The values of the select are defined in the controller. How do I load the page and the selects to be selected with the object values?

For example, if the value of the project type is 2, select is selected with option 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: #, the solution was to use a value of type string instead of number, but I did the test and did not work, the curious thing is that it seems to change the option and return to the default very fast.

    
asked by anonymous 25.01.2017 / 14:02

2 answers

0

I resolved by changing the ng-options and the vm.tipos list. It looks 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 selects already comes with the option selected according to objeto of ng-model

    
25.01.2017 / 15:43
1

You will have to use one of the iteration modes on the object and produce every option therefrom.

You can use ng-repeat or ng-options . I prefer ng-options because we do not have to do the interpolation of our output once the directive addresses that.

Without changing your code structure, it is 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 ng-options directive to iterate over our types object that contains the type value and type name.

You have the JSFiddle

    
25.01.2017 / 15:44