jisaak jisaak - 6 months ago 10
AngularJS Question

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

Answer

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>

Comments