Nesh
Nesh

Reputation: 2541

Getting blank option in second select dependent on first select option - AngularJS

Following is the code which is working fine, the only issue I am facing is that the second option value on first time(until not selected) is coming blank. Le t me know what I am doing wrong here.

Code -

<div>
    <h3>Select a country</h3>
    <select id="select-02" 
            class="slds-select" 
            name="country" 
            ng-model="myForm.companyaddress.country" 
            ng-options="conList.name for conList in countryList track by conList.id"
            ng-init="myForm.companyaddress.country = countryList[0]"
            ng-change="stateList = myForm.companyaddress.country.states"
            style="height: 37px;">
    </select>
</div>

<div>
    <h3>Select a state</h3>
    <select
      id="select-03"
      class="slds-select"
      style="height: 44px;"
      ng-init="myForm.companyaddress.state = countryList[0].states[0]"
      ng-options="sList.name for sList in stateList track by sList.stateid"
      ng-model="myForm.companyaddress.state">
    </select>
</div>

Script -

    var myApp = angular.module('myApp', []);

    myApp.controller('mainCtrl', function($scope){

        $scope.countryList = [
            {
                id: null,
                name: 'Please Select',
                states: [
                    {name: 'Please Select', stateid: null}
                ]
            },
            {
              id: 1,
              name: 'United States of America',
              states: [
              {name: 'Alabama', stateid: 1},
              {name: 'Alaska', stateid: 2},
              {name: 'Arizona', stateid: 3}
              ]
            },
            {
              id: 2,
              name: 'Australia',
              states: [
              {name: 'Australian Capital Territory', stateid: 1},
              {name: 'New South Wales', stateid: 2},
              {name: 'Northern Territory', stateid: 3}
              ]
            },
        ];

        $scope.stateList = $scope.countryList[0].states;
    })

Working Plnkr - http://plnkr.co/edit/ZYmMJG8CbxrpdOjuUh9k?p=preview

Upvotes: 0

Views: 26

Answers (1)

Juan&#237;n
Juan&#237;n

Reputation: 851

The problem I see so far is that once you selected a country the myForm.companyaddress.state option is not on the list of options so it's blank

You can change your first ng-change for this

ng-change="stateList = myForm.companyaddress.country.states; myForm.companyaddress.state =  stateList[0]"

Check this plnkr

http://plnkr.co/edit/ZYmMJG8CbxrpdOjuUh9k

Upvotes: 1

Related Questions