预先在Angular JS中填充ng-repeat中的下拉值

时间:2015-03-30 06:40:25

标签: javascript angularjs drop-down-menu ng-options

我有一个对象数组。我有三个属性attorneyId, attorneyName and attorneyListattorneyList数组应该是下拉列表。如果是attorneyId = attorneyName = null那么 下拉列表只会显示Choose attorney。如果attorneyId != nullattorneyName != null,下拉列表应显示attorneyIdattorneyName中的值。

为此,我正在准备一个对象selectedAttorney = {id:list.attorneyId, name:list.attorneyName}并将其传递给select ng-model。当我更改下拉列表中的值时,我会在selectedAttorney中获得正确的值。但是,如果attorneyIdattorneyName存在某些值,则下拉列表不会预先填充该值。

HTML:

<div ng-repeat = 'list in List'>
  <div class="width-200" ng-init="selectedAttorney = {id:list.attorneyId, name:list.attorneyName}">
    {{selectedAttorney}}
    <select ng-model="selectedAttorney" ng-options="attorney.name for attorney in list.attorneyList">
      <option value="">-- choose attorney --</option>
    </select>
  </div>
</div>

JS

$scope.List = [ {
  "attorneyId": "3",
  "attorneyName": "Robert",
  "attorneyList": [
    { "id": 1, "name": "sue" },
    { "id": 2, "name": "anthony" },
    { "id": 3, "name": "Robert" },
    { "id": 4, "name": "George" },
    { "id": 5, "name": "Bruce" }
  ]
},
{
  "attorneyId": null,
  "attorneyName": null,
  "attorneyList": [
    { "id": 1, "name": "sue" },
    { "id": 2, "name": "anthony" },
    { "id": 3, "name": "Robert" },
    { "id": 4, "name": "George" },
    { "id": 5, "name": "Bruce" }
  ]
}
];

以下是plunker链接。

http://plnkr.co/edit/eqBkX0DNleiFmlO5sm7J?p=preview

提前致谢。

1 个答案:

答案 0 :(得分:2)

虽然你的方法是正确的,但我更喜欢以这种方式编写我的选择框。

<select ng-model="selectedAttorney">
        <option 
           ng-repeat="attorney in list.attorneyList"
           title="{{attorney.name}}"
           ng-selected="{{attorney.id == selectedAttorney.id}}"
           value="{{attorney}}">{{attorney.name}}
       </option>
</select>

这是更新的工作演示:http://plnkr.co/edit/vCNOAPWlR6Mj1kFOgCKT?p=preview