AngularJS: dependent dropdown menus

Attempting to create a cascade dropdown in Angular, I assumed it would work seamlessly with binding. Here is the code snippet:

<select name="client" ng-model="selectedRequest.client" ng-options="c.name for c in clients track by c.id" required></select>
<select id="department" ng-model="selectedRequest.department" ng-options="d.defaultLabel for d in selectedRequest.client.departments track by d.id"></select>

Initially, when the view loads, it functions correctly displaying departments associated with the selected client. However, upon changing the selected client, the department dropdown empties instead of updating as expected.

EDIT

I modified the child dropdown to :

<select id="department" ng-model="selectedRequest.department" ng-options="d.defaultLabel for d in departments track by d.id | filter:{clientId: selectedRequest.client.id}"></select>

This time, all departments are loaded into the dropdown irrespective of the filter applied.

** EDIT 2 **

Updated to :

<select name="client" ng-model="requestService.selectedRequest.client" ng-options="c as c.name for c in clients track by c.id" required></select>

 <select id="department" ng-model="requestService.selectedRequest.department" ng-options="d.defaultLabel for d in departments  | filter:{clientId: requestService.selectedRequest.client.id}"></select>

Now, selecting a client triggers the source change correctly. However, setting the initial department at startup fails due to the removal of 'track by id'.

Answer №1

the right approach is as follows:

<select id="department" ng-model="selectedRequest.department" ng-options="d.defaultLabel for d in departments | filter:{clientId: selectedRequest.client.id} track by d.id "></select>

I simply overlooked placing the filter correctly... a simple oversight.

Answer №2

It is possible that the object referenced by selectedRequest.client is not the same as the objects in the clients array. You can try the following solution:

JavaScript:

function exampleFunction($scope) {
            $scope.clients = [
             { id: 1, name: "client1", departments: [{ id: 1, defaultLabel: 'department1' }, { id: 2, defaultLabel: 'department2'}] },
             { id: 2, name: "client2", departments: [{ id: 3, defaultLabel: 'department3' }, { id: 4, defaultLabel: 'department4'}] }
            ];

             $scope.selectedRequest = {};
             $scope.selectedRequest.client = $scope.clients[0];//Assign by object reference.
        }

HTML:

<div ng-controller="exampleFunction">
        <select name="client" ng-model="selectedRequest.client" ng-options="c.name for c in clients" required></select>
        <select id="department" ng-model="selectedRequest.department" ng-options="d.defaultLabel for d in selectedRequest.client.departments"></select>
    </div>

Check out the live demo here!

I have removed the track by to use the default (track by object reference) method and ensure that selectedRequest.client refers to objects within the clients array.

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

In JavaScript, provide a boolean response to a callback function from a separate function

Working with the jQuery validate plugin involves utilizing a submitHandler callback function. This function determines whether the form submission should proceed based on its return value - false will prevent submission, while true will allow it to go thro ...

The setState function in React Native seems to be having trouble updating

I've been attempting to access state from a component, but for some reason, I'm not seeing any changes when I use setState(). Here is the current state of my component: class MyTestComponent extends React.Component { constructor(props){ ...

Using Angular JS to dynamically load an HTML template from a directive upon clicking a button

When a link is clicked, I am attempting to load an HTML template. A directive has been created with the templateUrl attribute to load the HTML file. Upon clicking the link, a function is called to append a custom directive "myCustomer" to a pre-existing di ...

Effortless link to a Gremlin database using a JavaScript app

I apologize for my lack of technical knowledge, but I am struggling to solve this issue despite studying the documentation. My goal is to establish a connection with a standard Gremlin DB (Cosmos) using gremlin. While it works well from the server, encoun ...

Error in Prisma: Unable to retrieve data due to undefined properties (attempting to access 'findMany')

Recently, I've been working on a dashboard app using Prisma, Next.js, and supabase. Encountering an issue with the EventChart model in schema.prisma, I decided to create a new model called EventAreaChart. However, after migrating and attempting to ex ...

When an option is selected in one dropdown, a list is dynamically populated in another dropdown. However, the entire column then displays the selected row's options in a table format

https://i.stack.imgur.com/q7tMT.png Upon selecting an option from a dropdown within a table row, I make a call to an API to fetch a list of strings into another dropdown field for that specific row. However, the entire column is being populated with that r ...

The Express server is set up with CORS enabled, however, it continues to encounter issues when attempting to make asynchronous HTTP requests from

We're currently experiencing an unusual issue and are seeking assistance to resolve it. Initially, our Express server is functioning well as an API when accessed from the same domain. However, we also need to utilize this API on our computers for tes ...

Unable to hear sound properly through Web Audio

I'm experimenting with playing a wav file using the AudioContext. I've noticed that it plays correctly when loaded with the <audio> tag (as demonstrated in this example on jsFiddle), but encounters issues when using AudioContext. var startB ...

Focus event in IE does not always work as expected after an ajax request is

Our current focus is on supporting IE8 exclusively. An ajax call retrieves data from the server, replaces the HTML in a container div with the response, and then attempts to focus on an element within the response. However, there seems to be inconsistenci ...

Adjust the sidebar size in Bootstrap 5 to align perfectly with the navbar brand

https://i.stack.imgur.com/Ra0c7.png I'm trying to ensure that the width of the sidebar on this page aligns consistently with the end of the logo in the top right. However, using variations of col-xxl-1 etc. is causing inconsistent sizes at different ...

What could be causing render_template to fail when attempting to update the same parameters more than once?

Lately, I've dived into the world of Flask, MongoDB, and ElasticSearch. So far, my MongoDB and ElasticSearch setups are running smoothly. However, I've encountered an issue with generating a list of dictionaries and displaying them on my HTML we ...

How to return a variable to Express when clicking a button?

Imagine having a list of 10 elements, each with a unique id as their name, and the user has the ability to add more items to the list at any time. If I were to click on an element, my goal is to have Express retrieve the id of that specific element. If it ...

The functionality of the controls is not functioning properly when attempting to play a video after clicking on an image in HTML5

While working with two HTML5 videos, I encountered an issue with the play/pause functionality. Despite writing Javascript code to control this, clicking on one video's poster sometimes results in the other video playing instead. This inconsistency is ...

The marriage of Vue 2.0 and Rails 5: Shifting from Reactive to Declarative Rendering

As I make my way through the Vue guide with a Rails 5 app, I've noticed that although I am able to update my Vue js object, the DOM doesn't behave as described in the Declarative Rendering section. The data and the DOM are supposed to be linke ...

Enhance your iPhone web app with high-resolution retina images!

As I develop a mobile web application accessible on any smartphone, I have the index.html file available for review: The app includes 2 jQuery functions. One detects if the user is using an iPhone and displays a bubble with instructions to add it to the h ...

Transforming an Ext.data.TreeStore data structure into a JSON format

How can I convert an Ext.data.TreeStore to a string for saving to Local Storage? I tried using Ext.encode() but it's giving me a circular structure error. Has anyone encountered this issue and found a workaround? ...

Tips for retrieving a child component's content children in Angular 2

Having an issue with Angular 2. The Main component displays the menu, and it has a child component called Tabs. This Tabs component dynamically adds Tab components when menu items are clicked in the Main component. Using @ContentChildren in the Tabs comp ...

I am unable to select the first item when using select2.js and setting a placeholder

I am experiencing an issue with my <select> list that is styled using select2.js. Everything seems to be functioning properly, except for when a placeholder is used. Users are unable to select the first item in the list initially. If they choose any ...

Tips for maintaining authentication in a Next.js application with Firebase even when tokens expire or the page is refreshed

Struggling with firebase authentication flows while building an app using firebase and next.js. Everything was going smoothly until I encountered a bug or error. When my computer remains logged in to the app for some time and I refresh the page, it redirec ...

Tips for adjusting the autocomplete maxitem dynamically

I am working on a multi autocomplete feature and I have the following code. Is there a way to dynamically set the maximum number of items based on the value entered in another text field? <script> $(function () { var url2 = "<?php echo SI ...