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

Exploring the realm of variable scope in JavaScript and Vue.JS

I am a newcomer to JavaScript and I have encountered an issue with the scope of my object/variable. Can you please help me understand why my {endtoken:this.token} is empty, while console.log({rawToken:e.data}) is not? I find the concept of variable scope ...

Unable to reset the input value to an empty string

I have created a table with a search bar feature that filters the data when the search button is clicked and resets the filter to show unfiltered data when the clear button is clicked. However, the current input value is not clearing from the display even ...

Using AngularJS controllers: How can one trigger a controller from within a different controller?

Within my script, I have a list controller defined as follows: define([ 'jquery', 'app' ], function ($,app) { app.controller("ListContacts", function($scope,$route,$http){ $http({ method: 'GET&apo ...

Unable to invoke parent method from child component in Vue causing issue

I am facing an issue where I am trying to trigger a method in the parent component from the child component using $emit, but for some reason, it is not working as expected. Can someone please help me troubleshoot this problem? Parent Component <templat ...

JavaScript - turn off online connectivity

Is there a way to test my website for offline use by disabling connectivity on the bootstrap before anything loads, so that all data will be loaded from cache? I have tried various offline libraries such as this one, but I haven't found a way to prog ...

How to trigger an update of the useEffect() hook when a button is clicked

I am working with a functional component that contains a button and uses the "useEffect()" hook. My goal is to trigger a re-render of the component, updating the useEffect() hook when the button is clicked. const Emp_list = (props) => { useEffect(() ...

When defining a class property in TypeScript, you can make it optional by not providing

Is there a way to make a property on a Class optional without it being undefined? In the following example, note that the Class constructor takes a type of itself (this is intentional) class Test { foo: number; bar: string; baz?: string; construc ...

A pop-up modal that remains closed thanks to sessionStorage

I've been working on creating a modal that pops up after a short delay, but once closed, it shouldn't appear again unless the user closes the website and starts a new session. While I have successfully designed the modal, integrating sessionStora ...

Struggling to set up the connection between React-Redux connect and the Provider store

Currently utilizing Redux with React Native for state management. I've set up the store and Provider successfully it seems, as I can utilize store.getState() and store.dispatch(action()) from any component without issue. However, I'm encountering ...

Transferring an organized array to processing

My goal is to transfer an array of integers from a php file called load.php to a JS script, which will then forward it to a Processing file written in JavaScript. In load.php, I define the array and send it using JSON (the array contains a minimum of 40 i ...

How to update the date format in v-text-field

I have run into an issue while working on a Vue.js project that utilizes Vuetify. The problem lies with the default date format of the v-text-field when its type is set to "date." Currently, the format shows as mm/dd/yyyy, but I need it to display in the y ...

Having trouble with Next.js getStaticProps? Getting a TypeError that says "Cannot read properties of undefined (reading 'map')"?

My latest project was built using create-next-app as a base. In the Blog.js page, I attempted to fetch data from https://jsonplaceholder.typicode.com/posts by utilizing the getStaticProps() function. I followed the instructions provided in this guide: htt ...

Unable to access the URL slug within the client component in Next.js version 13

In my upcoming project with Next 13, I have a client-side component that is being rendered under the route /journal/[date] Unfortunately, I'm facing an issue trying to extract the date from the URL. I attempted to use: import { useRouter } from &apos ...

Is there any way to remove the two default aspNetHidden Divs in asp.net web forms?

After creating an empty webform page in asp.net, the generated code looks like this: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="Threetier.WebForm1" %> <!DOCTYPE html> <html xmlns="http://www.w3.org ...

The absence of jasmine-node assertions in promises goes unnoticed

Everything seems to be running smoothly with the code below, except for the assertion part. Whenever I run the test using Jasmine, it reports 0 assertions. Is there a way to include my assertions within promises so they are recognized? it("should open sav ...

When clicking to open the md-select on Angular Material 1.1.0, an unwanted [object object] is being appended

Every time I try to open the md-select input, an [object Object] (string) is added to the body tag. Click here to see the md-select input After clicking the md-select once, this is how the body looks ...

Optimal Placement for FB.Event.subscribe

Here is the code I have implemented on my website for the Facebook Like and Share buttons. The functionality works seamlessly. When I click the Like button, a notification is promptly displayed on my Facebook profile page. Additionally, Facebook automatic ...

Exploring ways to cycle through a select dropdown in React by utilizing properties sent from the Parent Component

I'm having trouble displaying the props from a parent component in a modal, specifically in a select dropdown. How can I make it so that the dropdown dynamically shows the values from the props instead of the hardcoded 'Agent' value? What am ...

Using AngularJS and JavaScript, set the Submit button to be enabled only when the email input is valid and a value is selected in

I'm trying to create a form that includes an email input field and a drop-down list sourced from a database array. Initially, the submit button is disabled when the form loads. My goal is to figure out how to activate the submit button only when the ...

The ng-grid in Angular fails to update when changes are made from a modal dialog

There is a form on the page that consists of textboxes and a submit button. Upon entering values in the textboxes and clicking the submit button, a grid is displayed. The grid contains multiple columns with a delete button at the end of each row. Clicking ...