33

Fiddle with the relevant code: http://jsfiddle.net/gFCzV/7/

I'm trying to set the selected value of a drop down that is bound to a child collection of an object referenced in an ng-repeat. I don't know how to set the selected option since I can't reference the collection it's being bound to in any way that I'm aware of.

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"
    }];
});

Is this the one case where I should actually be using ng-init with a SelectedIndex on the model?

4

3 回答 3

80

如果使用 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/

于 2014-08-09T13:12:10.353 回答
32

您可以将该ID字段用作相等标识符。在这种情况下,您不能使用 adhoc 对象,因为 AngularJS在比较对象时会检查引用是否相等。

<select 
    ng-model="Choice.SelectedOption.ID" 
    ng-options="choice.ID as choice.Name for choice in Choice.Options">
</select>
于 2013-12-30T18:36:11.303 回答
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>

于 2016-01-21T07:19:53.383 回答