forgottofly
forgottofly

Reputation: 2719

Switching between two select drop down in angular js

I'm having two drop down list .with JSON data

<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'}];

My requirement:If I select an Item in first drop down then second select dropdown should be autofilled with its first item,and vice versa.

Any help will be really apreciated.Thanks

Upvotes: 1

Views: 628

Answers (1)

Kalhan.Toress
Kalhan.Toress

Reputation: 21901

edit the first ng-options as below

<select class="form control" ng-model="fruitsName" ng-options="r as r.name for r in fruits" ng-change="selectSecond()">
<option value="">--Select---</option>

inside the 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;    
}

here is the Demo Plunker


if you are not interested in changing the 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>

then your controller should be like

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

here is the Demo Plunker


if you need the vice versa do the same

here is the Demo Plunker

Upvotes: 1

Related Questions