我已按照以下链接解决问题,但它没有奏效: 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>
但是,这不会显示所选文本。我做错了什么?
答案 0 :(得分:7)
它不显示所选文本,因为您的模型将具有所选项目的ID,因为在ng-options中使用s.id as s.hostName
(select as label syntax
)。只需从语法中删除select as
部分,让ng-model保持所选对象的引用本身而不仅仅是id。
所以你的ng-option: -
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 强>
答案 1 :(得分:3)
尝试此功能:
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>