Unleashing the power of AngularJS to create dynamic interactions between

Is there anyone who can assist me in getting my Country/State drop down dependency example to work?

The reason I structured the JSON in this manner is because I want the dependency to be versatile, allowing me to apply it to any drop down using only Meta Data instead of HTML markup.

If you'd like to view the code example on JSFiddle, here's the link.

HTML Code:

Country:<select data-ng-model="Countries" data-ng-options="country.id as country.name for country in Countries.items">
            <option value="">Please select a country</option>
        </select>

State: <select data-ng-model="currentItem" data-ng-options="item.id as item.name for item in currentStates.items">
            <option value="">Please select a state</option>
        </select>

JavaScript Code:

function Controller($scope) {

var Countries = {
    "id": "field10",
    "items": [{
                "id": "10",
                "StateGroupID":"0",
                "name": "United State"
              }, 
              {
                 "id": "2",
                 "StateGroupID":"1",
                 "name": "Canada"
              }]
};

var States =
    {   "id": "field20",
        "StateGroups": [{
            "items": [{  "id": "1",
                       "name": "Alabama"
                      }, 
                      {
                          "id": "2",
                          "name": "Alaska"
                      }, 
                      {  "id": "3",
                       "name": "Arizona"
                      }, 
                      {  "id": "4",
                       "name": "California"
                      }]},

                 [{  "id": "201",
                    "name": "Alberta"
                   }, 
                  {
                      "id": "202",
                      "name": "British Columbia"
                  }, 
                  {
                      "id": "303",
                      "name": "Manitoba"
                  }, 
                  {
                      "id": "304",
                      "name": "Ontario"
                  }]]
};

$scope.Countries = Countries;
$scope.currentStates = States.StateGroups[0];
$scope.$watch('currentStates', function(value, oldValue){
    
});
}

Answer №1

Initially, it seems like there is a slight error in your JSON format. You need to have an "items" key before listing the Canadian states.


{"items": [{  "id": "201",
            "name": "Alberta"
           }, .....

Once you make this correction, I recommend adjusting your HTML to support two separate model names and utilizing a different ng-repeat syntax to assign values based on the StateGroupId.


<select data-ng-model="selectedCountry">
    <option ng-repeat='country in Countries.items' value='{{country.StateGroupID}}'>{{country.name}}</option>          
</select>

This approach enables you to create a function that retrieves the states belonging to the selected group ID:


$scope.getStates=function(){
    console.log($scope.selectedCountry)
     return $scope.backupStates.StateGroups[$scope.selectedCountry].items;
}

You can then utilize this function for displaying the states using ng-repeat:


        <select data-ng-model="selectedState" >
          <option value="">Please select a state</option>
          <option ng-repeat='state in getStates()'>{{state.name}}</option>
        </select>

I've made adjustments to your original fiddle here: http://jsfiddle.net/DotDotDot/TsxTU/14/. I hope this aligns with the intended functionality you were aiming for :)

Answer №2

To improve your data model organization, I recommend separating counties and states into two different arrays:

$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
}];

With this structure in place, you can create select elements for the data:

<select data-ng-model="country" data-ng-options="country.name for country in countries" data-ng-change="updateCountry()">
  <option value="">Select country</option>
</select>
<select data-ng-model="state" data-ng-options="state.name for state in availableStates">
  <option value="">Select state</option>
</select>

It would be convenient to use if expressions directly in selectors, but since that's not possible, we need a bit of JavaScript:

$scope.updateCountry = function(){
  $scope.availableStates = [];

  angular.forEach($scope.states, function(value){
    if (value.countryId == $scope.country.id){
      $scope.availableStates.push(value);
    }
  });
}

And that's it! Feel free to check out the working plunk here.

Answer №3

To easily resolve this issue, simply reference the currentCountry in the second select tag and avoid using the $watch function to meet your needs.

<select data-ng-model="currentCountry" data-ng-options="country.name for country in Countries.items">

<select data-ng-model="currentItem" data-ng-options="item.id as item.name for item in States.StateGroups[currentCountry.StateGroupID].items">

View Demo

Answer №4

angular-country-picker To add the angular-country-picker to your project, you can use either of the following commands: - bower install angular-country-picker - npm install angular-country-picker

<script src="bower_components/angular-country-picker/country-picker.js"></script>
<script src="node_modules/angular-country-picker/country-picker.js"></script>

       You can then integrate the country picker into your Angular module as follows:

       angular.module('webApp', ['puigcerber.countryPicker']);

       <select ng-model="selectedCountry" pvp-country-picker="name"></select>

       Additionally, you can customize the list of countries by providing a configuration like this in your Angular module:

       angular.module('myApp', ['puigcerber.countryPicker'])
       .config(function(pvpCountriesProvider) {
        pvpCountriesProvider.setCountries([
        { name: 'Abkhazia', alpha2: 'AB'},
        { name: 'Kosovo', alpha2: 'XK'},
        { name: 'Nagorno-Karabakh', alpha2: 'NK'},
        { name: 'Northern Cyprus', alpha2: 'KK'},
        { name: 'Somaliland', alpha2: 'JS'},
        { name: 'South Ossetia', alpha2: 'XI'},
        { name: 'Transnistria', alpha2: 'PF'}
      ]);
    });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Implementing Oauth in Angular and Node

I am facing challenges with implementing oauth in Angular. When I directly enter the link into the browser http://localhost:8080/auth/twitter I am able to successfully connect using oauth and receive a response. However, when I try to achieve the same in ...

Attempt to efficiently register components automatically on a global scale in Vue by utilizing the powerful combination of Laravel-Mix and Webpack

In my previous projects with Vue, which were based in a Laravel-Mix/Webpack runtime environment, I used to individually register components and views as needed. This was done by importing them and extending Vue: import BaseButton from './components/Ba ...

Retrieve a value from a different collection in MongoDb

Is it possible to copy certain fields from one collection to another? I am looking to copy the values of 'bar' to the 'foo' collection, excluding the 'type' field. Additionally, I want to add a new _id and an extra field (use ...

Tips for implementing async/await with the file system module

Can you explain the approach to deleting a file using the async/await syntax in combination with fs.unlink() for a specified path? ...

Request with content Type multipart/form experienced Error 406

I encountered an issue with my axios request in Express const formData = new FormData(); formData.append("file", fs.createReadStream(file.path)); formData.append("requestid", '123456'); const options = { method: 'POST& ...

Fetching weather data from the Darksky.com API in JSON format

My goal is to retrieve weather data in JSON format from the Darksky.com API. To do this, I first successfully obtained my latitude and longitude using the freegoip.com API. However, the Darksky API requires both longitude and latitude before it can provid ...

``There seems to be an issue with VueJs v-for loop not updating

Having an issue with a form where buttons to add children inputs stop working after adding one child. There seems to be an error in the console, but when checking the data output it appears the new input box is being added. The DOM just isn't updating ...

Eliminating rows from a DataTable through an Ajax request

I have a DataTables table from datatables.net with a custom column containing icons for various actions. One of these actions is deleting a row without reloading the data. I'm looking for a built-in function to remove datatable rows locally after dele ...

Examine both statements at the same time

The concept: I am in the process of creating a bot that will access Instagram using puppeteer. If the login is successful, the bot will continue as normal. However, if an error with ID slfErrorAlert occurs during login, the bot will stop. The issue: ...

Every change to the data in Nuxt.js triggers a form submission

This is my form: <template> <div class="flex flex-col mt-[5rem] gap-4 p-4 items-center max-w-4xl mx-auto"> <form id="inquiry" class="flex flex-col gap-4 w-full" @submit.prevent="submitHand ...

Retrieve evenly spaced keys from the center of an array

I am working with some JavaScript code that is meant to extract the first and last elements from an array, then incrementally include the remaining elements. For example: var numbers = ['One', 'Two', 'Three', 'Four&apos ...

Avoid duplicate calls to the same URL in node.js

I need to make multiple calls to the back-end with some of them targeting the same URLs. To optimize performance, I am caching the results. However, a problem arises when I call loadCached twice in quick succession with the same URL - it ends up triggering ...

Tips for implementing a multi-layered accumulation system with the reduce function

Consider the following scenario: const elements = [ { fieldA: true }, { fieldB: true }, { fieldA: true, fieldB: true }, { fieldB: true }, { fieldB: true }, ]; const [withFieldA, withoutFieldA] = elements.reduce( (acc, entry) => ...

Unable to permanently uninstall Node.js

I recently downloaded the forever package using the command: npm install forever -g However, when I attempted to uninstall it using: npm uninstall -g forever I received the message up to date in 0.042s Despite this, I am still able to access the forev ...

In Internet Explorer 8, the jQuery UI Tooltip is closing abruptly

Scenario We are encountering an issue with a jQuery UI tooltip that is triggered by a mouseenter event on the <div class="fieldset"> (.fieldset) element within a form. The problem arises in IE8, where the tooltip disappears immediately upon hovering ...

Issue with Jeditable feature on the Castle Monorail platform

Exploring the use of Jeditables (http://www.appelsiini.net/projects/jeditable) within my debut castle monorail mvc application Successfully displayed the textbox and executed the ajax call. However, encountering an issue post ajax call where the edited te ...

Utilize multipart/form-data to upload several files and retrieve them within Vue.js

My recent project involved uploading a single file using form-data and fetch (POST request) successfully. However, I encountered an issue when trying to upload multiple files. Here is the code snippet in question: In the HTML part of my vue.js: <el-but ...

Tips for finding the index of data in Cesium

After successfully completing the tutorial on building a flight tracker, I am facing a challenge. I want to access the current index of my data at any given time while my app is running cesium and displaying the airplane animation following the flight path ...

Tips for transferring a JavaScript variable to a Java servlet using the doPost method

I am working with an HTML table that contains dropdowns. When a user clicks on a dropdown, I store the column name and corresponding row (billdate) in a variable. Now, my goal is to pass this variable to my Java servlet's doPost method and then use it ...

Get a document from Angular.js utilizing Express.js

For my MEAN application, I have a requirement to securely provide a hidden link for users to download files. My solution involves storing the files on the server directory and using Angular.js to send an HTTP request to express.js with the file ID for down ...