繁体   English   中英

如何获取所选选项的索引<select>在 angularjs 中

[英]How to get the index of the selected option in <select> in angularjs

我是 angularJS 代码的新手。

我正在尝试显示将显示几个选项的下拉列表。

在我的选择元素下方,我想根据用户从上面的下拉列表中选择显示一些文本。

要选择相关文本,我需要从下拉列表中知道所选项目的索引或位置。

这是我的代码的样子。

<select name="selUsers"
        ng-model="activeUser"
        ng-options="user.name as user.name for user in userOptions"
        required>
    <option value="" disabled="disabled">
      Choose...
    </option>
</select>

<span>
//need to display text based on above selection
</span>

有人可以在这里帮助我如何获取所选项目的索引吗?

谢谢你。

运行一个函数来检查选择选项每次更改的索引...

下面的工作片段

 var app = angular.module('myApp', []); app.controller('myCtrl', function($scope) { $scope.names = ["Emil", "Tobias", "Linus"]; $scope.detectIndex = () => { for (var i = 0; i < $scope.names.length; i++) { if ($scope.names[i] == $scope.selectedName) { $scope.selectedIndex = i; return; } } } });
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script> <div ng-app="myApp" ng-controller="myCtrl" ng-init="selectedIndex = null"> <select ng-model="selectedName" ng-options="x for x in names" ng-change="detectIndex()"> <option value="" disabled="disabled"> Choose... </option> </select> <p>you selected: {{ selectedName }} at index: {{ selectedIndex }}</p> </div>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM