Search code examples
javascriptarraysangularjsng-optionsangularjs-ng-options

Hide selected option in other list using ngOptions in AngularJS


Hoping someone can help with this challenge.

I have 1 array of airports being used in two build separate dropdowns.

<select data-ng-model="flightData.origin" data-ng-options="airport.code as airport.label for airport in flightData.airports" name="origin"></select>

and

<select data-ng-model="flightData.destination" data-ng-options="airport.code as airport.label for airport in flightData.airports" name="destination"></select>

Both of these lists obviously have the same options. What I would like to do is when you select for example "Sydney" in the origin, to remove "Sydney" from the destination dropdown.

For reference, this is an example of what the airport data looks like.

this.airports = [{
    code: "TSV",
    label: "Townsville",
}, {
    code: "PER",
    label: "Perth",
}, {
    code: "BNE",
    label: "Brisbane",
}, {
    code: "MEL",
    label: "Melbourne",
}, {
    code: "KGI",
    label: "Kalgoorlie",
}, {
    code: "SYD",
    label: "Sydney",
},{
    code: "LAX",
    label: "Los Angeles",
}, {
    code: "JFK",
    label: "New York",
}, {
    code: "DEL",
    label: "New Dehli",
}];

I understand I will most likely need two separate arrays (1 for origins, and 1 for destinations), just not sure how to approach it.

Thanks!


Solution

  • use ng-change and also you need two list.

    <select data-ng-model="flightData.airports_origin" ng-change="changeOrigin()" data-ng-options="airport.code as airport.label for airport in flightData.airports" name="origin"></select>
    
    <select data-ng-model="flightData.airports_destination"  data-ng-options="airport.code as airport.label for airport in flightData.airports" name="origin"></select>
    

    In your controller, inject filterFilter and then search for the selected airport in available destination airports list and remove it.

    // in your controller
    $scope.airports_origin      = angular.copy(this.airport); 
    $scope.airports_destination = angular.copy(this.airport);
    $scope.changeOrigin = function(){
        var selected_origin = flightData.origin;
        var destination_airport = filterFilter(this.airports_destination,{'code':selected_origin.code})[0];
        $scope.airports_destination.splice($scope.airports_destination.indexOf(destination_airport),1);
    
    }