AngularJS Cascading Dropdown Object ng-option Error Detected

I found a helpful example at this link: . It's working well, but I am encountering an issue where I get the object with an index number instead of the expected value.

Here is my controller:


/**
* @ngdoc object
* @name test.Controllers.TestController
* @description TestController
* @requires ng.$scope
*/

angular
.module('test')
.controller('TestController', [
    '$scope',
    function($scope) {
        $scope.countries = {
            'India': {
                'Maharashtra': ['Pune', 'Mumbai', 'Nagpur', 'Akola'],
                'Madhya Pradesh': ['Indore', 'Bhopal', 'Jabalpur'],
                'Rajasthan': ['Jaipur', 'Ajmer', 'Jodhpur']
            },
            'USA': {
                'Alabama': ['Montgomery', 'Birmingham'],
                'California': ['Sacramento', 'Fremont'],
                'Illinois': ['Springfield', 'Chicago']
            },
            'Australia': {
                'New South Wales': ['Sydney'],
                'Victoria': ['Melbourne']
            }
        };
        $scope.GetSelectedCountry = function () {
            $scope.strCountry = document.getElementById("country").value;
            var datas =$scope.strCountry;
            console.log(JSON.stringify(datas));
        };
        $scope.GetSelectedState = function () {
            $scope.strState = document.getElementById("state").value;
        };



    }
]);

On my view page:

Country: Select   States:Select   City: Select {{city}}   Selected Country: {{strCountry}}   Selected State: {{strState}}   Selected City: {{city}}

Answer №1

If you're looking to retrieve the chosen country and state, you can loop through the object to find the key that corresponds to the ng-model value. For obtaining the city, simply return the value of ng-model.

angular.module('test', [])
  .controller('TestController', ['$scope',
      function($scope) {
        $scope.countries = {
          'India': {
            'Maharashtra': ['Pune', 'Mumbai', 'Nagpur', 'Akola'],
            'Madhya Pradesh': ['Indore', 'Bhopal', 'Jabalpur'],
            'Rajasthan': ['Jaipur', 'Ajmer', 'Jodhpur']
          },
          'USA': {
            'Alabama': ['Montgomery', 'Birmingham'],
            'California': ['Sacramento', 'Fremont'],
            'Illinois': ['Springfield', 'Chicago']
          },
          'Australia': {
            'New South Wales': ['Sydney'],
            'Victoria': ['Melbourne']
          }
        };

        $scope.getCountry = function(val) {
          for (var key in $scope.countries) {
            if ($scope.countries.hasOwnProperty(key)) {
              if ($scope.countries[key] === val) {
                alert('You chose: ' + key);
              }
            }
          }
        };
        
        $scope.getCity = function(city, state) {
          for (var key in state) {
            if (state.hasOwnProperty(key)) {
              if (state[key] === city) {
                alert('You selected: ' + key);
              }
            }
          }
        };

        $scope.alertCity = function(city) {
          alert('You picked ' + city);
        };
  }]);
<script src="https://code.angularjs.org/1.3.15/angular.min.js"></script>

<div ng-app="test">
  <div ng-controller="TestController">
    <div>
      Country:
      <select id="country" ng-model="states" ng-options="country for (country, states) in countries" ng-change="getCountry(states)">
        <option value=''>Select</option>
      </select>
    </div>
    <div>
      States:
      <select id="state" ng-disabled="!states" ng-model="cities" ng-options="state for (state,city) in states" ng-change="getCity(cities, states)">
        <option value=''>Select</option>
      </select>
    </div>
    <div>
      City:
      <select id="city" ng-disabled="!cities || !states" ng-model="city" ng-change="alertCity(city)">
        <option value=''>Select</option>
        <option ng-repeat="city in cities" value="{{city}}">{{city}}</option>
      </select>
    </div>
  </div>
</div>

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

Challenges with downloading a file synchronously using NodeJS

Having trouble with writing files synchronously in my local application using the 'download-file-sync' module. When I use 'writeFileSync', the file size doubles even though the content seems to be identical to a file downloaded through ...

Guide on aligning a popup next to the button that activated it using CSS and JavaScript

I am currently generating a dynamic quantity of divs, each containing a button that triggers a popup when clicked. I am attempting to position the popup below the specific button that activated it, but it remains static and does not move accordingly. <d ...

After ajax, trigger change event

Can anyone assist me in combining multiple functions within the same form using AJAX? The purpose of the form is to prenote a new "meeting" and it consists of an input for the date and a select dropdown for choosing the operator. FORM CODE: <div id=&qu ...

Angular 5 Auto Complete Feature

How can I implement a typeahead feature for an input tag in Angular? I want to retrieve a list of users from the database as the user types, and then be able to save the selected user. <input id="txtpreparer" type="text" class="validate form-control" r ...

Encountered an error with a JSON object in node and express: Unexpected colon token

I'm currently in the process of developing a small web service using Node.js and Express, and I've encountered an issue. It all runs smoothly until I attempt to utilize it with Ajax in a web browser. When I test it in Postman, everything works fi ...

Searching for data in Node.js using Mongoose and dates

I'm in search of a way to execute a specific query with mongoose. In my mongodb database, I have data structured like this: "startDateTime" : ISODate("2017-03-22T00:00:00.000Z"), "endDateTime" : ISODate("2017-03-27T00:00:00.000Z"), My goal is to r ...

Is there a way to prevent redirection to the homepage after submitting a login form?

Having trouble with my Single Page application: every time I refresh the page after rendering the login form, it goes back to the homepage. How can I prevent this and make sure the page stays on the login form even after a refresh? This is what my homepag ...

Exploring the 3D Carousel Effect with jQuery

After creating a 3D carousel using jQuery and CSS3, I am looking to enhance it with swiping support. While there are plenty of libraries available for detecting swipes, I specifically want the carousel to start rotating slowly when the user swipes slowly. ...

Using Array Data Format to Customize Color in Highcharts Funnel Chart

I have included the funnel visualization code that I've been working on. $(function() { var dataEx = [ ['1 Visit', 352000], ['2 Visits', 88000], ['3+ Visits', 42000] ], len = dataEx.length, ...

Unable to load CSS and JS files on JSP servlet mapping

When there is no servlet mapped to a / in the servlet mapping: <servlet-mapping> <servlet-name>ControllerServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> All my css and javascript framewor ...

Failure to achieve closure - even after thorough study of the concept

I have a countdown that I'm trying to get working during onload, but I'm running into issues with closures. Here is my code: Check out the fiddle here for (var o in myDates) { var myDate = myDates[o]; var iid = o; funcs[o] = function() { ...

Angular 13.0 version is experiencing issues when trying to run the "ng serve" command

After installing the npm module, I encountered a problem while using node.js version 14.17.6. I am a beginner in Angular and struggling to find a solution due to not using the latest Angular CLI version. Any help would be greatly appreciated. Thank you in ...

Complicated aspects of React and Angular deployment

As I delve into learning React, I find myself a bit puzzled by the various aspects of development and deployment. Are all webpages built using frameworks like React or Angular? Or are they primarily used for single page web applications? Can React be serv ...

What is the best way to create a PHP array using JSON?

Is there a way to create a JSON-based array using the json_encode() function in PHP? I am looking for help on achieving the following array format: callback([{"ProductID":1,"ProductName":"Chai","UnitPrice":18,"UnitsInStock":39,"Discontinued":false}]) Als ...

"How can we pause the setInterval when the user hovers over the Ajax Quick Cart and resume it once

Currently, I am working on configuring my Ajax Quick Cart to delay a setInterval function when the user hovers over the cart. The goal is to have the cart close automatically after 3 seconds once an item has been added. However, as I'm not very profic ...

formula for an arbitrary velocity vector

In the game I'm developing, I want the ball to move in a random direction on the HTML canvas when it starts, but always with the same velocity. The current code I have is: vx = Math.floor(Math.random() * 20) vy = Math.floor(Math.random() * 20) Howev ...

Change the text to uppercase format

As a novice, I'm looking to create an event that triggers upon the change of input. The text entered in the input should automatically be formatted as follows: The first letter should always be capitalized; All other letters should be in lowercase. ...

Transfer individual values from one array to another in a deconstructed manner

Can someone help me with utilizing the ES6 array.prototype methods effectively? I am trying to map the attributes object and extract the attribute_label values into a new array. It is crucial to ensure that the value is not null. The desired outcome is a ...

Sending Python Object from Django View to Javascript Script in Template

Here is a basic code snippet created solely to illustrate a problem. While the task at hand can be achieved without JavaScript, I am exploring how to accomplish it using JavaScript for my actual code where it is necessary. In view.py Inside the play_game ...

Best practices for Django project implementation using only pure JavaScript, HTML, and template tags

As a newcomer to website development, my decision to use Django was influenced by my familiarity with Python and the complexity of the project at hand. I am seeking advice on the best practices for creating templates using the Django framework. My query i ...