user3421352
user3421352

Reputation: 101

How to dynamically change values in drop down using other drop down change using angular?

I have two drop downs. Initially both has values like "First","Second","Third",... When 1st dropdown has value "First" the second should not offer a value "First" that is second should have other than what is selected from 1st one. I want to do this using angularjs. Values in 2nd dropdown should be changed dynamically.

<select class="form-control" ng-model="Data.firstType">
  <option>First</option>
  <option>Second</option>
  <option>Third</option>
</select>

<select class="form-control" ng-model="Data.SecondType">
  <option>First</option>
  <option>Second</option>
  <option>Third</option>
</select>

Can anyone help on this?

Thanks in advance.

Upvotes: 1

Views: 5546

Answers (2)

Brocco
Brocco

Reputation: 65053

If you're items in the drop downs are static you can do this fiddle

ng-if="Data.FirstType !== First"

If they are dynamic then you can filter the items in the second list based upon the item selected in the first drop down

Here is a fiddle to dynamically filter the second list if the lists are being populated dynamically.

function MyCtrl($scope){
    $scope.Data = {};
    $scope.items = [{id:1, name:'First'}, {id:2, name:'Second'}, {id:3, name:'Third'}];
    $scope.exclude = function(x){
        return x !== $scope.Data.firstType;
    }
}

Upvotes: 4

Matt Cashatt
Matt Cashatt

Reputation: 24238

Just use a $watch:

$scope.$watch('Data.firstType', function(val) {
    //Get index of type in Data.yourArrayData
    var idx = $scope.Data.yourArrayData.indexOf(val);
    $scope.Data.yourArrayData.splice(idx, 1);
});

This assumes you are binding your second select to yourArrayData using an ng-repeat. I haven't tested this code, but it should be what you need.

Upvotes: 0

Related Questions