Configuración de valores seleccionados para ng-options bound select elements
Juega con el código correspondiente: http://jsfiddle.net/gFCzV/7 /
Estoy tratando de establecer el valor seleccionado de un menú desplegable que está vinculado a una colección secundaria de un objeto al que se hace referencia en un ng-repeat. No se cómo configurar la opción seleccionada ya que no puedo hacer referencia a la colección a la que está vinculada de ninguna manera que yo sepa.
HTML :
<div ng-app="myApp" ng-controller="SomeController">
<div ng-repeat="Person in People">
<div class="listheader">{{Person.firstName}} {{Person.lastName}}</div>
<div class="listitem" ng-repeat="Choice in Person.Choices">
{{Choice.Name}}:
<select
ng-model="Choice.SelectedOption"
ng-options="choice.Name for choice in Choice.Options"></select>
{{Choice.SelectedOption.ID}}
</div>
</div>
</div>
JS :
var myApp = angular.module('myApp', []);
myApp.controller("SomeController", function($scope) {
$scope.People = [{
"firstName": "John",
"lastName": "Doe",
"Choices": [
{
"Name":"Dinner",
"Options":[{Name:"Fish",ID:1}, {Name:"Chicken",ID:2}, {Name:"Beef",ID:3}],
"SelectedOption":{Name:"Chicken",ID:2} //this doesn't work
},
{
"Name":"Lunch",
"Options":[{Name:"Macaroni",ID:1}, {Name:"PB&J",ID:2}, {Name:"Fish",ID:3}],
"SelectedOption":""
}
],
}, {
"firstName": "Jane",
"lastName": "Doe"
}];
});
Es este el único caso en el que debería estar usando ng-init con un SelectedIndex en el modelo?
3 answers
Si usa AngularJS 1.2 puede usar 'track by' para decirle a Angular cómo comparar objetos.
<select
ng-model="Choice.SelectedOption"
ng-options="choice.Name for choice in Choice.Options track by choice.ID">
</select>
Fiddle actualizado http://jsfiddle.net/gFCzV/34 /
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
2014-09-03 21:46:46
Puede usar el campo ID
como identificador de igualdad. No se puede utilizar el objeto adhoc para este caso porque AngularJS comprueba referencias igualdad al comparar objetos.
<select
ng-model="Choice.SelectedOption.ID"
ng-options="choice.ID as choice.Name for choice in Choice.Options">
</select>
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
2013-12-30 18:36:11
Usando ng-selected para el valor seleccionado. He implementado con éxito el código en AngularJS v1. 3. 2
<select ng-model="objBillingAddress.StateId" >
<option data-ng-repeat="c in States" value="{{c.StateId}}" ng-selected="objBillingAddress.BillingStateId==c.StateId">{{c.StateName}}</option>
</select>
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-01-21 07:19:53