【问题标题】:Angular JS - get selected text of a select controlAngular JS - 获取选择控件的选定文本
【发布时间】:2014-09-21 15:56:42
【问题描述】:
我已经按照以下链接解决了这个问题,但没有奏效:
How to get option text value using AngularJS?
我有一个包含一组服务器的下拉列表。当我从下拉列表中选择一个值时,我希望所选值显示在单独的 div 中。这是我所做的:
选择控件:
<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>
显示选定的文本:
<span class="pull-left">Source: {{ filterOptions.hostId.hostName }}</span>
但是,这不会显示选定的文本。我做错了什么?
【问题讨论】:
标签:
angularjs
angularjs-ng-options
angularjs-ng-model
【解决方案1】:
它不显示选定的文本,因为在 ng-options 中使用了s.id as s.hostName (select as label syntax),因此您的模型将具有选定项目的 id。只需从语法中删除 select as 部分,让 ng-model 保存所选对象的引用本身,而不仅仅是 id。
所以你的 ng 选项:-
ng-model="filterOptions.host"
ng-options="s.hostName for s in physicalServerList track by s.id"
您的模型将成为选定对象,而不仅仅是选定项的 id
<span class="pull-left">Source: {{ filterOptions.host.hostName }}</span>
Plnkr
【解决方案2】:
试试这个功能:
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>