PyReda PyReda - 1 year ago 66
AngularJS Question

angularjs dependant dropdown option value

i have successfully set up a dependant dropdown using angularjs, but i have a little problem:

i need to define the value of every option tag because it is set up automatically by angular processor.

here is my html code:

<div ng-controller="CountryCntrl">

<select id="country" ng-model="states" ng-options="country for (country, states) in countries">
<option value=''>Choose</option>

<select id="state" ng-disabled="!states">
<option value="">Choose</option>
<option ng-repeat="state in states" value="{{}}">{{state.dep}}</option>

<input type="submit" value="go">

and here is my angularjs code:

var Aplic = angular.module("Aplic", []);

Aplic.controller('CountryCntrl', function($scope){

$scope.countries = {
'Aquitaine': [ {'id':'22', 'dep': "Dordogne"}, { 'id':'31', 'dep' : "Gironde"} ],
'Auvergne': [ {'id' : '3', 'dep' : "Allier"}, {'id' : '15', 'dep' : "Cantal"} ]


I repeat, i have successfully set up the value for the option in the second dropdown, but for the first one it takes automatically the name of variable country.

so how should i change my code to give every option tag in the first dropdown a specific value.

to understand well my idea, please inspect the values in every dropdown. here is my working snippet on plunker:

any help will be appreciated.

here is what i want to do:

<select id="state" ng-model="cou">
<option value="">Choisir</option>
<option ng-repeat="cou in countries" value="{{}}">{{}}</option>

<select id="state" ng-disabled="!cou">
<option value="">Choisir</option>
<option ng-repeat="state in cou.states" value="{{}}">{{state.dep}}</option>

but now the second dropdown does not work, if you can fiw that the problemwill be solved

Answer Source

Here is sample implementation for you. This will keep values in option tag.

<div ng-app="Aplic" ng-controller="CountryCntrl">
    <select id="country" ng-model="selectedCountry" ng-options=" as for country  in countries track by">
        <option value="">Choose</option>
    <select id="state"
    ng-options=" as state.dep for state in ((countries | filter:{'id':selectedCountry})[0].states) track by">
        <option value="">Choose</option>

    <div>selectedCountry id: {{selectedCountry}}</div>
    <div>selectedState id: {{selectedState}}</div>


 $scope.countries =[
     'id': '1',
      'name': "Aquitaine",
      'states': [{
         'id': '22',
         'dep': "Dordogne"
     }, {
         'id': '31',
         'dep': "Gironde"
     'id': '2',
      'name': "Auvergne",
      'states':  [{
         'id': '3',
         'dep': "Allier"
     }, {
         'id': '15',
         'dep': "Cantal"

Working demo