0

I am using ng-options to populate my select. I assign the value to be the id of the field however I need to assign the description of my option as well.

Not sure how to do that without iterating through my list separately afterwards to find the matching id.

So I am assigning the user's id to the vm.model.user but how can I possibly assign name to a different variable and still make this generic. The key part is this being generic as the description name might vary (sometimes it's description or userDescription etc. and I cannot control that).

$scope.users = [
  { id: 1, name: 'John' },
  { id: 2, name: 'Adam' },
  { id: 3, name: 'Chloe' },
  { id: 4, name: 'Chris' }
];
<select ng-model="vm.model.user" ng-options="user.id as user.name for user in users | orderBy: 'name'"></select>

I have tried doing this on ng-change but it seems it is not aware of user, only ng-options is.

ng-change="vm.model.userDescription = user.name"

LazioTibijczyk
  • 1,701
  • 21
  • 48

2 Answers2

0

One solution would be to set ng-model with the the selected user object, so vm.model.user would have both id and name:

<select ng-model="vm.model.user" ng-options="user as user.name for user in vm.users | orderBy: 'name'"></select>

Check demo: DEMO

Bill P
  • 3,622
  • 10
  • 20
  • 32
0

I found this interesting answer https://stackoverflow.com/a/28323031/9559251

Basically we could just do

ng-change="vm.model.userDescription = (users | filter: {id: vm.model.user})[0].name"

LazioTibijczyk
  • 1,701
  • 21
  • 48
  • Not sure if I should ever care about the efficiency of running a filter on the list of options as it doesn't look like the 'cleanest' solution. – LazioTibijczyk Dec 06 '19 at 15:57