Javascript 具有多个字段的 AngularJS ng-options
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13602335/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
AngularJS ng-options with several fields
提问by ChruS
I have a collection of objects with user info.
我有一组包含用户信息的对象。
"Id": "1",
"Firstname": "ABCDEF",
"Lastname": "GHIJK",
"Middlename": ""
In my select options I want to display two fields - Firstname Lastname. I don't get how to do it and how to bind it to ng-model.
在我的选择选项中,我想显示两个字段 - Firstname Lastname. 我不知道该怎么做以及如何将它绑定到ng-model.
回答by Maxence
You can try this :
你可以试试这个:
<select
name="users"
ng-model="selectedUser"
ng-options="user.Id as user.Firstname + ' ' + user.Lastname for user in users">
</select>
More information in the documentation : https://docs.angularjs.org/api/ng/directive/select
文档中的更多信息:https: //docs.angularjs.org/api/ng/directive/select
回答by code_wrangler
Considering the format of your array object to be like this.
考虑到你的数组对象的格式是这样的。
$scope.userInfo = [
{"Id": "1", "Firstname": "ACDEF", "Lastname": "GHIJK", "Middlename": ""},
{"Id": "2", "Firstname": "BADEF", "Lastname": "HIGJK", "Middlename": ""},
{"Id": "3", "Firstname": "CDBEF", "Lastname": "IIHJK", "Middlename": ""},
]
You can display two fields like this and and bind it to the model as shown below.
您可以像这样显示两个字段并将其绑定到模型,如下所示。
<select ng-model="userInfo" ng-options="s.Firstname +' '+ s.Lastname for s in userInfo" class="span2"> </select>
回答by manoj
Just an additional update,
只是一个额外的更新,
I had to show the Last name enclosed in brackets so here is how I modified the answer and got it working.
我必须显示括在括号中的姓氏,因此这是我修改答案并使其正常工作的方式。
<select
name="users"
ng-model="selectedUser"
ng-options="user.Id as user.Firstname + ' (' + user.Lastname + ') ' for user in users">
</select>
回答by Juan Garassino
Theres is always in a non ng-optionsscenario, where you can bind two params from the ng-repeatitem:
总是在非ng-options场景中,您可以从ng-repeat项目中绑定两个参数:
<select name="user" ng-model="vm.asignedUser">
<option value="">Select user</option>
<option value="{{ {'name':user.name, 'id': user.id} }}" ng-repeat="user in vm.users">
{{ user.nombreLargo }}
</option>
</select>
回答by Scott
This worked for me:
这对我有用:
<select ng-model="color" ng-options="(c.name+' '+c.shade) for c in colors"></select>
<select ng-model="color" ng-options="(c.name+' '+c.shade) for c in colors"></select>
Source: https://groups.google.com/d/msg/angular/ljJd5x1Tgrk/bZuVWCA1hO4J
资料来源:https: //groups.google.com/d/msg/angular/ljJd5x1Tgrk/bZuVWCA1hO4J

