ChruS
ChruS

Reputation: 3747

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.

Upvotes: 44

Views: 33175

Answers (5)

Scott
Scott

Reputation: 782

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

Upvotes: 0

Maxence
Maxence

Reputation: 13388

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

Upvotes: 105

Juan Garassino
Juan Garassino

Reputation: 61

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>

Upvotes: 1

manoj
manoj

Reputation: 3791

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>

Upvotes: 3

code_wrangler
code_wrangler

Reputation: 1669

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> 

Upvotes: 14

Related Questions