簡體   English   中英

如何在角度設置選擇默認選項?

[英]How do I set select default option in angular?

所以我有從服務器檢索的json數據,如下所示:

$scope.StateList = {"States": [
    {
        "Id": 1,
        "Code": "AL",
        "Name": "Alabama"
    },
    {
        "Id": 2,
        "Code": "AK",
        "Name": "Alaska"
    },
    {
        "Id": 3,
        "Code": "AZ",
        "Name": "Arizona"
    },
    {
        "Id": 4,
        "Code": "AR",
        "Name": "Arkansas"
    }]}

$scope.Address = {"Address": {
    "Address1": "123 Maple" ,
    "Address2": null,
    "City": "Tempe",
    "State": "AZ",
    "ZipCode": null,
    "Country": null,
    "Id": 0,
    "Latitude": 0,
    "Longitude": 0
}}

我設置了一個如下所示的選擇:

  <select ng-model="Address.State">
    <option ng-repeat="template in StateList.States">{{template.Code}}</option>
  </select>

我需要能夠將Address.State字段綁定到所選的值,並將其作為select選項的初始值。 我無法確定這一點,並感謝任何能夠向我展示我所缺少的東西的人。 這是一個可以使用的實時版本的插件

您可以做的是使用ng-options指令和ngModel,讓angular為您創建選項。 嘗試這種方式:-

 <select ng-model="Address.Address.State" 
         ng-options="state.Code as state.Name for state in StateList.States"></select>

普倫克

基本上,這使用語法

“選擇”作為“數組”中“值”的“標簽”

您可以按照PSL的建議使用ng-options,也可以使用options的value屬性

<option ng-repeat="template in StateList.States" 
       value="{{template.Code}}">{{template.Code}}</option>

鏈接器

最好使用專門為選擇下拉列表提供的ng-options綁定,而不是提供迭代的ng-repeat 下面的標記將提供默認文本和下拉選項

<select ng-model='Address.State' ng-options="template.Code for template in StateList.States" >
    <option value=""> Select one </option>
</select>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM