Country/State Selection with AngularJS

  1. <html data-ng-app="app">  
  2.   
  3.     <head>  
  4.         <script data-require="[email protected]" data-semver="1.1.5" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.js"></script>  
  5.         <link rel="stylesheet" href="style.css" />  
  6.         <script src="script.js"></script>  
  7.     </head>  
  8.   
  9.     <body data-ng-controller="CountriesController">   
  10.       <select data-ng-model="country" data-ng-options="country.name for country in countries" data-ng-change="updateCountry()">  
  11.         <option value="">Select country</option>  
  12.       </select>   
  13.       <br>   
  14.           <select data-ng-model="state" data-ng-options="state.name for state in availableStates">  
  15.                 <option value="">Select state</option>  
  16.           </select>   
  17.       <br> Country: {{country}} <br> State: {{state}}   
  18.     </body>  
  19.   
  20. </html>  
  1. var app = angular.module("app", []);  
  2.   
  3. function CountriesController($scope)  
  4. {  
  5.     $scope.countries = [  
  6.     {  
  7.         "name""USA",  
  8.         "id": 1  
  9.     },  
  10.     {  
  11.         "name""Canada",  
  12.         "id": 2  
  13.     }];  
  14.     $scope.states = [  
  15.     {  
  16.         "name""Alabama",  
  17.         "id": 1,  
  18.         "countryId": 1  
  19.     },  
  20.     {  
  21.         "name""Alaska",  
  22.         "id": 2,  
  23.         "countryId": 1  
  24.     },  
  25.     {  
  26.         "name""Arizona",  
  27.         "id": 3,  
  28.         "countryId": 1  
  29.     },  
  30.     {  
  31.         "name""Alberta",  
  32.         "id": 4,  
  33.         "countryId": 2  
  34.     },  
  35.     {  
  36.         "name""British columbia",  
  37.         "id": 5,  
  38.         "countryId": 2  
  39.     }];  
  40.     $scope.updateCountry = function ()  
  41.     {  
  42.         $scope.availableStates = [];  
  43.         angular.forEach($scope.states, function (value)  
  44.         {  
  45.             if (value.countryId == $scope.country.id)  
  46.             {  
  47.                 $scope.availableStates.push(value);  
  48.             }  
  49.         });  
  50.     }  
  51. }