Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I suggest you a bit of refactoring to your data model - it seems tangled. Let's store counties and states in two arrays:</p> <pre><code>$scope.countries = [{ "name": "USA", "id": 1 },{ "name": "Canada", "id": 2 }]; $scope.states = [{ "name": "Alabama", "id": 1, "countryId": 1 }, { "name": "Alaska", "id": 2, "countryId": 1 }, { "name": "Arizona", "id": 3, "countryId": 1 }, { "name": "Alberta", "id": 4, "countryId": 2 }, { "name": "British columbia", "id": 5, "countryId": 2 }]; </code></pre> <p>Having this, we can write <a href="http://docs.angularjs.org/api/ng.directive%3aselect"><code>select</code></a>s for data:</p> <pre><code>&lt;select data-ng-model="country" data-ng-options="country.name for country in countries" data-ng-change="updateCountry()"&gt; &lt;option value=""&gt;Select country&lt;/option&gt; &lt;/select&gt; &lt;select data-ng-model="state" data-ng-options="state.name for state in availableStates"&gt; &lt;option value=""&gt;Select state&lt;/option&gt; &lt;/select&gt; </code></pre> <p>It's a pity we cannot use <code>if</code> expressions in selectors - if we can, we do not need a single line of JS! But we need:</p> <pre><code>$scope.updateCountry = function(){ $scope.availableStates = []; angular.forEach($scope.states, function(value){ if(value.countryId == $scope.country.id){ $scope.availableStates.push(value); } }); } </code></pre> <p>And that's all. <a href="http://plnkr.co/edit/mQvoxoSdFNTvkQxqt53n?p=preview">Here is a working plunk for you.</a></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload