Search code examples
javascriptangularjsng-options2-way-object-databindingangularjs-ng-model

How to auto select another option in angularjs using ng-options


I have two select option and am using ng-options to get the data from json files. My concern is if a value is selected in first select, i need to automatically choose a corresponding value in the other select. I am able to populate the data in the dropdowns. but am unable to connect the two. Please help.

Below is my code for first select:

<select ng-model="firstType"
                            ng-change="firstTypeChange()"
                            ng-options="firstValue as firstValue.value group by firstValue.group for firstValue in firstList" tabindex="1">
                            <option value=""></option>
                    </select>    

And the second select is as follows:

<select ng-model="secondType"
                            ng-change="secondTypeChange()"
                            ng-options="secondValue as secondValue.value group by secondValue.group for secondValue in secondList"
                            tabindex="2">
                            <option value=""></option>
                    </select>    

And this is my code from controller:

$scope.firstType = "";
$scope.secondType = "";
$scope.isFirstTypeShow = true;
$scope.isSecondTypeShow = true;

$scope.firstTypeChange = function() {
$scope.formType = $scope.firstType.formType;
 if ($scope.firstType.formType == 'inquiry') {
   $scope.isSecondTypeShow = false;
 } else if ($scope.firstType.formType != 'inquiry' || $scope.firstType.formType == null) {
   $scope.isSecondTypeShow = true;
 } else if ($scope.formType == 'known'){
   $scope.secondType.formType = 'existing';
 }
}
$scope.secondTypeChange = function() { $scope.secondFormType = $scope.secondType.formType;};

Solution

  • You have a problem with your second if statement

    if ($scope.firstType.formType != 'inquiry' || $scope.firstType.formType == null) {
    

    you already know from the first if statement this $scope.firstType.formType != 'inquiry' is true, which means this if statement is always true and the last if statement never gets reached.

    The last if still wouldn't work though, you need to assign a value from your secondList to $scope.secondType to select the value. Check it out here JSFiddle

    $scope.firstTypeChange = function () {
        $scope.formType = $scope.firstType.value;   
        if ($scope.formType == 'inquiry') {
            $scope.isSecondTypeShow = false;
        } else if ($scope.formType == null) {
            $scope.isSecondTypeShow = true;
        }
        else if ($scope.formType == 'known') {
            $scope.secondType = $filter('filter')($scope.secondList, {value:'existing'})[0];
            $scope.isSecondTypeShow = true;
        }
        else {
            $scope.isSecondTypeShow = true;
        }
    }