摆弄相关代码: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" }]; });
这是我实际上应该在模型上将ng-init与SelectedIndex一起使用的一种情况吗?
如果使用AngularJS 1.2,则可以使用“ track by”来告诉Angular如何比较对象。
<select ng-model="Choice.SelectedOption" ng-options="choice.Name for choice in Choice.Options track by choice.ID"> </select>
更新小提琴http://jsfiddle.net/gFCzV/34/