摆弄相关代码:http://jsfiddle.net/gFCzV/7/
我正在尝试设置下拉列表的选定值,该下拉列表绑定到ng-repeat中引用的对象的子集合。我不知道如何设置所选的选项,因为我无法以我所知的任何方式引用它所绑定的集合。
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"
}];
});
这是我应该在模型上使用带有SelectedIndex的ng-init的情况吗?
答案 0 :(得分:78)
如果使用AngularJS 1.2,您可以使用&#39;跟踪&#39;告诉Angular如何比较对象。
<select
ng-model="Choice.SelectedOption"
ng-options="choice.Name for choice in Choice.Options track by choice.ID">
</select>
答案 1 :(得分:32)
您可以使用ID
字段作为等号标识符。您不能在这种情况下使用adhoc对象,因为AngularJS在比较对象时检查引用相等。
<select
ng-model="Choice.SelectedOption.ID"
ng-options="choice.ID as choice.Name for choice in Choice.Options">
</select>
答案 2 :(得分:10)
对所选值使用 ng-selected 。我已经在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>
&#13;