在角度 js 中的两个选择下拉列表之间切换

Switching between two select drop down in angular js

本文关键字:选择 两个 下拉列表 之间 js      更新时间:2023-09-26

>我有两个下拉列表.with 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>

控制器内部

 $scope.selectSecond = function(obj) {
     var selected = $scope.fruitsName;
     var index = $scope.fruits.indexOf(selected);
     $scope.selectedFroutIndex = index;
     $scope.sellerName = $scope.seller[$scope.selectedFroutIndex].id;    
}

这是演示普伦克


如果您对更改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>

那么你的控制器应该像

$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;
}

这是演示普伦克


如果您需要反之亦然,请做同样的事情

这是演示普伦克