Select with angular loading blank value

5

Well I want the select to start with a selected value, this value already comes in my ng-model:

   <label class="format">SELECIONE:</label>
        <span class="format">
            <select   name="grupo" id="grupo"  data-ng-model="vm.grupoSelecionado.codigo">
                <option  data-ng-repeat="grupo in vm.listaGrupos" value="{{ grupo.codigo }}">{{grupo.descricao}}</option>
            </select>
        </span>

That is, my vm.groupSelected.code already comes my selected value, the same is within the list of ng-repeat, how to start it loaded?

    
asked by anonymous 06.10.2015 / 15:18

2 answers

3

Use ng-options as the source of your data. When present in a SELECT element, it allows the default selection of the value denoted by the key track by .

In the following example I used the same object present in your question ( vm ) to demonstrate this behavior:

function SampleController($scope) {
  $scope.vm = {
    listaGrupos: [
      {codigo: 'a', descricao: 'Grupo A'},
      {codigo: 'b', descricao: 'Grupo B'},
    ],
    grupoSelecionado: {grupo: {codigo: 'b'}} 
  };
}
<html ng-app>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script></head><body><divng-controller="SampleController">

      <label class="format">SELECIONE:</label>
      <span class="format">
        <select name="grupo" id="grupo"
                data-ng-model="vm.grupoSelecionado.grupo"
                ng-options="g.descricao for g in vm.listaGrupos track by g.codigo"
                >
        </select>
      </span>
      <br/>
      Selecionado: {{ vm.grupoSelecionado }}

    </div>
  </body>
</html>

When executing this code, notice that the SELECT element is initialized with group B pre-selected.

    
06.10.2015 / 16:07
2

I think there's something missing from your (angular) JavaScript to work.

Example:

var app = angular.module("app", []);
app.controller("ctrl", function($scope)
{
    $scope.id = {'id': 1};
    $scope.list = [
        {'id': 1, 'name': 'comunidade'},
        {'id': 2, 'name': 'csharp'}
    ];
});

In this javascript (angular) code I have set id to where my select should select.

In my HTML it would look like this:

<div ng-app="app" ng-controller="ctrl">
   <select id="select1" name="select1" ng-model="id" ng-options="s.name for s in list track by s.id">
   </select>
<div>

var app = angular.module("app", []);
app.controller("ctrl", function($scope)
{
    $scope.id = {'id': 1};
    $scope.list = [
        {'id': 1, 'name': 'comunidade'},
        {'id': 2, 'name': 'csharp'}
    ];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script><divng-app="app" ng-controller="ctrl">
<select id="select1" name="select1" ng-model="id" ng-options="s.name for s in list track by s.id">
</select>
<div>
    
06.10.2015 / 15:44