Problema:
Tengo un elemento SELECT en mi página, que se completa con ng-repeat . También tiene un ng-model que tiene un valor predeterminado.
Cuando cambio el valor, el ng-model adapta, está bien. Pero la lista desplegable muestra una ranura vacía 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 } };Puede usar la directiva ng-selected en los elementos de opción. Toma expresión que si es veraz 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>Manifestación
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>prueba el siguiente código:
En tu 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 tu página:
<select ng-model="data" ng-options="opt as opt.label for opt in units "> </select>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>