Struggling to dynamically generate dropdowns with AngularJS


  • I am working with 3 dropdown menus, named A, B, and C.
  • When an option is selected in dropdown A, it populates dropdown B.
  • Following that, when an option is chosen in dropdown B, it fills dropdown C.

    I have successfully implemented the first two steps. However, I am facing difficulties in achieving the third step.

    Here is a link to the code on jsFiddle.

Answer №1

How do you feel about this code snippet?

<div data-ng-app data-ng-controller="myCtrl">
  <select data-ng-model="option1" data-ng-options="option for option in options1 " data-ng-change="getOptions2($index)">
  </select>
  <select data-ng-model="option2" data-ng-options="option for option in options2" data-ng-show='options2.length' data-ng-change="getOptions3()">
  </select>
  <select data-ng-model="option3" data-ng-options="option for option in options3" data-ng-show='options3.length'>
  </select>
</div>


function myCtrl($scope) {
  $scope.options1 = option1Choices;
  $scope.options2 = []; // will be populated later
  $scope.options3 = [];
  $scope.getOptions2 = function() {
    $scope.options2 = option2Choices[option1Choices.indexOf($scope.option1)];
    $scope.getOptions3();
  };

  $scope.getOptions3 = function() {
 var combinedOptions=[].concat.apply([], option2Choices )
$scope.options3 = option3Choices[combinedOptions.indexOf($scope.option2)];
  }
}

View the live example here

Answer №2

The reason you are encountering difficulty with the third point is because your action is dependent on dropdown A having a value, rather than dropdown B. By adding a new trigger for dropdown B and implementing the same functionality as it relates to B, you will be able to achieve the desired outcome.

Here are the steps to follow:

<select data-ng-model="option2" data-ng-options="option for option in options2" data-ng-show='options2.length' data-ng-change="getOptions3()">

Next, create a function in your controller to update the options for dropdown C:

$scope.getOptions3 = function() {
    var key2 = $scope.options2.indexOf($scope.option2);
    var updatedOptions = option3Options[key2];
    $scope.options3 = updatedOptions;
};

I have made the necessary changes to your fiddle: http://jsfiddle.net/Xku9z/1196/

Answer №3

It seems that you have overlooked calling the getOption2() function to fetch option3

<select data-ng-model="option2" data-ng-options="option for option in options2" data-ng-show='options2.length' data-ng-change="getOptions2()">
</select>

Check out this Fiddler link for more information: http://jsfiddle.net/Xku9z/1198/

Answer №4

If I were in your shoes, I'd recommend updating the drop-downs to invoke different functions. This way, you won't be defining the third set of options prematurely. I have confirmed its functionality on JSFiddle.

Rather than...

function myCtrl($scope) {
  $scope.options1 = option1Options;
  $scope.options2 = []; // we'll retrieve these later
  $scope.options3 = [];
  $scope.getOptions2 = function() {

    var key = $scope.options1.indexOf($scope.option1);
    var key2 = $scope.options2.indexOf($scope.option2);
    var myNewOptions = option2Options[key];
    var myNewNewOptions = option3Options[key2];
    $scope.options2 = myNewOptions;
    $scope.options3 = myNewNewOptions;
  };
}

Utilize this instead...

function myCtrl($scope) {
  $scope.options1 = option1Options;
  $scope.options2 = []; // we'll get these later
  $scope.options3 = [];
  $scope.getOptions2 = function() {
    var key = $scope.options1.indexOf($scope.option1);
    var myNewOptions = option2Options[key];
    $scope.options2 = myNewOptions;
  };
    $scope.getOptions3 = function() {
    var key2 = $scope.options2.indexOf($scope.option2);
    var myNewNewOptions = option3Options[key2];
    $scope.options3 = myNewNewOptions;
  };
}

Remember to add data-ng-change="getOptions3()" to your second select tag.

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

Custom HTML form created by Ryan Fait with additional unique elements

My current script for styling checkboxes and radiobuttons is working perfectly: The issue arises when I dynamically add checkboxes and radiobuttons to the page using jQuery. The new elements do not inherit the custom styling. Is there a workaround for th ...

Guide to integrating custom fields in Wordpress with mapbox-gl js to generate map markers

Currently, I am in the process of generating a map that will display various points using Mapbox and WordPress. To achieve this, I have set up a custom post type within WordPress where the coordinates are stored in custom meta fields. Although the fields h ...

Ways to insert text at the start and end of JSON data in order to convert it into JSONP format

Currently, I am working on a project where I need to add a prefix "bio(" and a suffix ")" to my JSON data in order to make it callable as JSONP manually. I have around 200 files that require this modification, which is why I am looking for a programmatic ...

Request with an HTTP header for authentication

Here's a straightforward question that may seem simple to some developers but could be tricky for beginners. So, my question is - how can I send an HTTP request from a browser when a user clicks a button and also add an authorization header to the re ...

Steps to display text in a div upon clicking on an image

I am trying to create an image with two DIVs separated by a black line. The left DIV will contain 4 images, and I want the following functionality: When a user clicks on any of the buttons in the left DIV, a corresponding text should be revealed in the ri ...

Tips for saving data to a file using the frontend

Is it possible for draw.io to write directly to a local file from my browser without the need for any server app or browser extension? I'm not referring to simply downloading a file, but actually writing to a file. For example, when creating a new dia ...

The combination of Angular and Browserify with ui.router states results in the error message "Uncaught object"

I am in need of a project structure that is more organized for small projects, especially when using angular-browserify seeders. Is it feasible to create an index file that requires all routes similar to this example (which uses RequireJS) My project reli ...

Setting up Raycasting in React-three-fiber: A Guide

I have been experimenting with setting up a scene in react-three-fiber that involves using a raycaster to detect object intersections. You can check out my Scene here. While researching, I came across examples like this one and this other example, but th ...

AngularJS enhances user experience by allowing textareas to expand upon click

I am just starting to learn about angular.js and I'm wondering how to add a text area when clicking on an image. ....... ..... ..... </thead> <tbody> <tr ng-repeat="stu in Studentlist"> <td>{{stu.rollno}}</td> <td> ...

Guide on passing a constant value as a parameter to a method using Vue.js

There are two input fields in my form. <input type="text" @keypress="onKeypress(e, 'min')"> <input type="text" @keypress="onKeypress(e, 'max')"> Within my component : methods: { onKeypress(e, type) { // Access the key ...

Display an alert popup upon closing the browser following a server-side verification

Need help with creating a server-side validation alert that appears when the user tries to close the browser, and prevents the page from closing after the alert is displayed. The solution must be done entirely in the Codebehind with no code in the aspx p ...

Adding scripts to a PartialView in MVC using Jquery's append function

My issue is with a JavaScript function that appends a PartialView into a div. Everything seems to work correctly, except for the fact that the PartialView contains some scripts enclosed within <script></script> tags. As a result, when these dyn ...

The project attempted to incorporate a modal and backdrop, however they were not recognized by the system

I'm trying to incorporate a modal and a backdrop into my project, but it doesn't seem to be acknowledging the import import { useState } from "react"; import Modal from "./Modal"; import Backdrop from "./Backdrop"; ...

What causes the return of undefined when accessing an item from an object?

In order to extract the item "Errors" from the data object provided below: {Id: 15, Date: "22-02-2019", Time: "22:45", Sport: "Football", Country: "United Kingdom", …} Bet: "Win" Bookie: "Bet365" Competition: "Premier League" Country: "U ...

Having trouble with the "Corrupted @import" error during grunt build?

As I embark on my journey to create my very first Angular application, I have encountered a roadblock. Using Yeoman and angular-generator, everything seemed to be running smoothly with "grunt serve." However, when I attempted to execute "grunt build," the ...

What is the reason behind PWA's ability to only be installed in development mode?

I am currently in the process of integrating PWA into my React project. When I use webpack-dev-server, I can see the PWA app that I can install on my computer. However, when I build the project using webpack and try to run it, I am unable to do so. webpac ...

What is the best way to format a JavaScript datetime to show in 12 hour AM/PM style?

What is the best way to format a JavaScript datetime object in the 12-hour clock (AM/PM) format? ...

When attempting to modify the date and time input within the table, I find that as soon as I begin typing the first number, it automatically triggers the edit mode

Is it possible to modify the input date and time within the table without triggering any actions until both values have been entered? The entered value should be displayed within the table for editing purposes. Here's an example: function myFuncti ...

The gauge created dynamically using the justgage plugin does not display the value

I am currently experimenting with dynamically adding gauges, and although they are displayed on the screen, the values being shown are incorrect. Even when the graph indicates a different value, it still displays 0. These gauges are triggered by an onclick ...

How can I use CSS3 to design a unique custom shape that fits this specific style?

I have some detailed graphs, but I want to display them using CSS shapes. I've been attempting to create css3 shapes that match my graphics (see attached image), but without success. How can I replicate these graphics? https://i.sstatic.net/2pxaW.pn ...