简体   繁体   中英

AngularJS ng-options with several fields

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 .

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

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> 

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>

Theres is always in a non ng-options scenario, where you can bind two params from the ng-repeat item:

  <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>

This worked for me:

<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

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