简体   繁体   English

如何在角度设置选择默认选项?

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

So I have json data that is retrieved from the server that looks like this: 所以我有从服务器检索的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
}}

I set up a select that looks like the following: 我设置了一个如下所示的选择:

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

I need to be able to get the Address.State field to be bound to the value selected, be the initial value of the select options. 我需要能够将Address.State字段绑定到所选的值,并将其作为select选项的初始值。 I have not be able to nail this one down and would be grateful for anyone who can show me what I am missing. 我无法确定这一点,并感谢任何能够向我展示我所缺少的东西的人。 Here is a plunker for a live version to work with. 这是一个可以使用的实时版本的插件

What you can do is to use ng-options directive and an ngModel and let angular create the options for you. 您可以做的是使用ng-options指令和ngModel,让angular为您创建选项。 Try this way:- 尝试这种方式:-

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

Plnkr 普伦克

Basically this uses the syntax 基本上,这使用语法

"select" as "label" for "value" in "array" “选择”作为“数组”中“值”的“标签”

you can either use ng-options as suggested by PSL or you can use value attribute of options 您可以按照PSL的建议使用ng-options,也可以使用options的value属性

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

PLUNKER LINK 链接器

It is preferred to use the ng-options binding provided specifically for select dropdowns instead of ng-repeat which provides for iteration. 最好使用专门为选择下拉列表提供的ng-options绑定,而不是提供迭代的ng-repeat The below markup will provide the default text and the dropdown options 下面的标记将提供默认文本和下拉选项

<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