为ng-options设置选定值绑定选择元素

son*_*lis 32 angularjs ng-options

摆弄相关代码: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>
Run Code Online (Sandbox Code Playgroud)

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"
    }];
});
Run Code Online (Sandbox Code Playgroud)

这是我应该在模型上使用带有SelectedIndex的ng-init的一种情况吗?

Ric*_*ltz 78

如果使用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>
Run Code Online (Sandbox Code Playgroud)

更新小提琴http://jsfiddle.net/gFCzV/34/

  • `track by`通过消除ng-selected不能与ng-options(+1)一起使用的必要性帮助我走上正轨 (4认同)

zs2*_*020 32

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

<select 
    ng-model="Choice.SelectedOption.ID" 
    ng-options="choice.ID as choice.Name for choice in Choice.Options">
</select>
Run Code Online (Sandbox Code Playgroud)


Raj*_*eev 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>
Run Code Online (Sandbox Code Playgroud)