Reputation: 1444
I've followed the following link to solve the issue but it didn't work: How to get option text value using AngularJS?
I have a dropdown that contains a set of servers. when i select a value from the dropdown, I want the selected value to display in a separate div. Here is what I have done:
Select control:
<select name="source" class="form-control input-sm"
ng-model="filterOptions.hostId"
ng-options="s.id as s.hostName for s in physicalServerList"
ng-style="{'width':'100%'}">
</select>
Displaying selected text:
<span class="pull-left">Source: {{ filterOptions.hostId.hostName }}</span>
However, this does not display the selected text. What am I doing wrong?
Upvotes: 5
Views: 29427
Reputation: 3394
Try this function:
var hostApp = angular.module('hostApp', []);
hostApp.controller('hostController', function($scope) {
$scope.options = [
{ value: '1', label:'hosting1' },
{ value: '2', label:'hosting2' },
{ value: '3', label:'hosting3' }
];
$scope.hostSelected = $scope.options[0];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="hostApp">
<div ng-controller="hostController">
<select ng-model="hostSelected"
ng-options="opt as opt.label for opt in options">
</select>
<div>value: {{ hostSelected.value }} <br />label: {{ hostSelected.label }}</div>
</div>
</div>
Upvotes: 4
Reputation: 123739
It does not display selected text because your model will have the id of the selected item because of the usage of s.id as s.hostName
(select as label syntax
) in the ng-options. Just remove the select as
part from the syntax, have the ng-model hold the selected object's reference itself instead of just the id.
So your ng-option:-
ng-model="filterOptions.host"
ng-options="s.hostName for s in physicalServerList track by s.id"
and your model will be the selected object instead of just the id of the selected item
<span class="pull-left">Source: {{ filterOptions.host.hostName }}</span>
Upvotes: 7