AngularJS-ng-modelo en una SELECCIÓN


JSfiddle

Problema:

Tengo un SELECT-element en mi página, que se rellena con un ng-repeat. También tiene un ng-model que tiene un valor predeterminado.

Cuando cambio el valor, el ng-model se adapta, eso está bien. Pero la lista desplegable muestra un espacio vacío en el lanzamiento, donde debería tener el elemento con el valor predeterminado seleccionado en su lugar.

Código

<div ng-app ng-controller="myCtrl">
    <select class="form-control" ng-change="unitChanged()" ng-model="data.unit">
         <option ng-repeat="item in units" ng-value="item.id">{{item.label}}</option>
    </select>
</div>

Con JS:

function myCtrl ($scope) {
    $scope.units = [
        {'id': 10, 'label': 'test1'},
        {'id': 27, 'label': 'test2'},
        {'id': 39, 'label': 'test3'},
    ]

        $scope.data = {
        'id': 1,
        'unit': 27
        }

};
Author: Jordumus, 2015-05-05

6 answers

Puede usar la directiva ng-selected en los elementos de opción. Toma la expresión que si truthy establecerá la propiedad seleccionada.

En este caso:

<option ng-selected="data.unit == item.id" 
        ng-repeat="item in units" 
        ng-value="item.id">{{item.label}}</option>

Demo

angular.module("app",[]).controller("myCtrl",function($scope) {
    $scope.units = [
        {'id': 10, 'label': 'test1'},
        {'id': 27, 'label': 'test2'},
        {'id': 39, 'label': 'test3'},
    ]

        $scope.data = {
        'id': 1,
        'unit': 27
        }

});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="myCtrl">
    <select class="form-control" ng-change="unitChanged()" ng-model="data.unit">
         <option ng-selected="data.unit == item.id" ng-repeat="item in units" ng-value="item.id">{{item.label}}</option>
    </select>
</div>
 61
Author: Patrick Evans,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-05 09:16:32

Intente el siguiente código:

En su controlador:

 function myCtrl ($scope) {
      $scope.units = [
         {'id': 10, 'label': 'test1'},
         {'id': 27, 'label': 'test2'},
         {'id': 39, 'label': 'test3'},
      ];

   $scope.data= $scope.units[0]; // Set by default the value "test1"
 };

En su página :

 <select ng-model="data" ng-options="opt as opt.label for opt in units ">
                </select>

Violín de trabajo

 16
Author: carton,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-05 09:55:11

No necesita definir etiquetas de opción, puede hacerlo usando la directiva ngOptions: https://docs.angularjs.org/api/ng/directive/ngOptions

<select class="form-control" ng-change="unitChanged()" ng-model="data.unit" ng-options="unit.id as unit.label for unit in units"></select>
 6
Author: Numyx,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-05 09:54:56

Sin embargo, ngOptions proporciona algunos beneficios como reducir la memoria y aumentar la velocidad al no crear un nuevo ámbito para cada instancia repetida. angular docs

La solución alternativa es la directiva use ng-init. Puede especificar la función que inicializará sus datos predeterminados.

$scope.init = function(){
            angular.forEach($scope.units, function(item){
                if(item.id === $scope.data.unit){
                    $scope.data.unit = item;
                }
            });
        } 

Ver jsfiddle

 3
Author: Aleksey Kiyanov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-05 09:58:08

También puede poner el elemento con el valor predeterminado seleccionado fuera del ng-repeat como sigue:

<div ng-app="app" ng-controller="myCtrl">
    <select class="form-control" ng-change="unitChanged()" ng-model="data.unit">
        <option value="yourDefaultValue">Default one</option>
        <option ng-selected="data.unit == item.id" ng-repeat="item in units" ng-value="item.id">{{item.label}}</option>
    </select>
</div>

Y no olvides el valor atribuute si lo dejas en blanco tendrás el mismo problema.

 2
Author: Ze Rubeus,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-11 09:39:43

El valor predeterminado de Select debe ser uno de sus valores en la lista. Para cargar el select con el valor predeterminado puede usar ng-options . Se debe establecer una variable de ámbito en el controlador y esa variable se asigna como ng-model en la etiqueta select de HTML.

Vea este émbolo para cualquier referencia:

Http://embed.plnkr.co/hQiYqaQXrtpxQ96gcZhq/preview

 1
Author: Alhuck A,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-05 09:47:03