Martin Brandl
Martin Brandl

Reputation: 58991

Bind a dropdown box selection to an Id of another object

I have a object list admins which contains a Username and Id property. Within a dropdown, I only display the Username property. If the user now selects an admin, I want to store the Id (not the username) into another object settings:

Here is what I have tried so far:

<select class="input-large" ng-model="vm.settings.selectedAdminId">
    <option ng-repeat="admin in vm.admins | orderBy:'Username'">{{admin.Username}}</option>
</select>

I am able to select a Username but I don't know how to store the selected admin.Id into settings.selectedAdminId

Upvotes: 1

Views: 35

Answers (2)

dfsq
dfsq

Reputation: 193311

First of all use ngOptions. Then it will be

<select class="input-large" 
    ng-model="vm.settings.selectedAdminId"
    ng-options="admin.Id as admin.Username for admin in vm.admins | orderBy:'Username'">
</select>

angular.module('demo', []).controller('DemoController', function() {
  this.admins = [
    {Id: 123, Username: 'Thomas'},
    {Id: 344, Username: 'Mann'}
  ]
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>

<div ng-app="demo" ng-controller="DemoController as vm">
  <select class="input-large" 
    ng-model="vm.settings.selectedAdminId" 
    ng-options="admin.Id as admin.Username for admin in vm.admins | orderBy:'Username'">
  </select>
  
  <p>Selected: {{ vm.settings.selectedAdminId }}</p>
</div>

Upvotes: 2

PRDeving
PRDeving

Reputation: 669

You could do it like this

<select class="input-large" ng-model="vm.settings.selectedAdminId">
    <option ng-repeat="admin in vm.admins | orderBy:'Username'" value="{{admin.Id}}">{{admin.Username}}</option>
</select>

Upvotes: 1

Related Questions