我有两个带有 JSON 数据的下拉列表
<select class="form control" ng-model="fruitsName" ng-options="r.id as r.name for r in fruits">
<option value="">--Select---</option></select>
$scope.fruits = [{'id': 'AL', 'name': 'Apple'},{'id': 'FL', 'name': 'Orange'},{'id': 'CA', 'name': Mango'},{'id': 'DE', 'name': 'PineApple'}];
<select class="form control" ng-model="sellerName" ng-options="r.id as r.name for r in seller">
<option value=""></option></select>
$scope.seller = [{'id': 'AL', 'name': 'John'},{'id': 'FL', 'name': 'Miller'},{'id': 'CA', 'name': 'Jack'},{'id': 'DE', 'name': 'Smith'}];
我的要求:如果我在第一个下拉列表中选择一个项目,那么第二个选择下拉列表应该自动填充其第一个项目,反之亦然。
任何帮助将非常感激。谢谢
最佳答案
编辑第一个ng-options
如下
<select class="form control" ng-model="fruitsName" ng-options="r as r.name for r in fruits" ng-change="selectSecond()">
<option value="">--Select---</option>
Controller 内部
$scope.selectSecond = function(obj) {
var selected = $scope.fruitsName;
var index = $scope.fruits.indexOf(selected);
$scope.selectedFroutIndex = index;
$scope.sellerName = $scope.seller[$scope.selectedFroutIndex].id;
}
这是演示 Plunker
<小时/>如果您对更改 ng-options
不感兴趣
<select class="form control" ng-model="fruitsName" ng-options="r.id as r.name for r in fruits" ng-change="selectSecond()">
<option value="">--Select---</option>
</select>
那么你的 Controller 应该是这样的
$scope.selectSecond = function() {
var selected = $scope.fruitsName;
var index = -1;
angular.forEach($scope.fruits , function(value, key) {
if(value.id === selected) {
index = key;
return;
}
})
$scope.selectedFroutIndex = index;
$scope.sellerName = $scope.seller[$scope.selectedFroutIndex].id;
}
这是演示 Plunker
<小时/>如果您需要反之亦然,请执行相同的操作
这是演示 Plunker
关于javascript - 在 Angular js中的两个选择下拉菜单之间切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27441135/