简体   繁体   中英

Setting default value for <select/> using ng-options with (key, value) in angularjs

I want to set a default value for the following select:

<select ng-model="selected"
      ng-options="key as value.Name for (key, value) in attributes">
</select>

I use attributes as a map with an id as key and an object as value. I want to show the name of the value in the select-box, but bind the key to the model, because when I access selected , I need the id, not the name. This works but now I want to set a default value. The default value must also show value.Name , but bind id .

According to this , it should work something like this:

$scope.selected = { 1: {Name : "Attribute1"}};

I haven't made it yet. I would appreciate any help.

EDIT:

My attributes variable looks like this (TypeScript):

export interface IAttributes {
    [id: number]: IAttributeProperties;
}

export interface IAttributeProperties {
    Name: string;
    DataType: string;
}

You can initialize it with ng-init :

<select 
      ng-init="selected = attributes[0]" 
      ng-model="selected"
      ng-options="key as value.Name for (key, value) in attributes">
</select>

The solution was to set the following default value:

$scope.selected = '1';

So I just needed to set the id (key). In the select box was displayed "Attribute1" now and the related id is bound.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM