Utilize dropdown1 to dynamically populate dropdown 2 in AngularJS

Here is the HTML code snippet I am currently working with:

<select ng-controller="category"  ng-model="selectedTestAccount" ng-options="c.category for c in categories track by c.categoryID" ></select>
<select ng-controller="subcategory"  ng-model="selectedTestAccount1" ng-options="c.subcategory for c in subcategories track by c.subcategoryID"></select>

I have structured my JSON data like this:

JSON1:

{"category": "Restaurants", "categoryID": "1"}

JSON2:

{"category": "Restaurants", "categoryID": "1", "subcategory": "European", "subcategoryID": "1"}
{"category": "Restaurants", "categoryID": "1", "subcategory": "Food Carts", "subcategoryID": "17"}

I would like to create two dropdowns. The first dropdown should display categories from the first JSON. Upon selecting a category, I want the second dropdown to dynamically list subcategories from the second JSON related to the selected category. How can I make the first dropdown mandatory? Any assistance would be greatly appreciated.

Answer №1

Behold, I have prepared a live example for you to explore.

The magic lies in the use of $watch, which monitors changes in the selected value (ng-model) of the first list and dynamically updates the options in the second list accordingly.

$scope.$watch('selectedCategory', function(newVal) {
  for (var j = 0; j < $scope.subCategories.length; j++){
    if ($scope.subCategories[j].name === newVal){
      $scope.selectedSubCategoryValues = $scope.subCategories[j].values;
    }
  }
});

Answer №2

Follow these steps:

  1. Add the mandatory attribute to the initial select element
  2. Include an empty <option></option> within the select (to ensure there is no pre-existing default option)

See this example for reference: http://jsfiddle.net/h7532w8c/1/

Answer №3

Utilize a wristwatch to observe the initial item. If it undergoes any modifications, adjust the array for the subsequent one. This action will modify the choices in accordance with your desired preferences.

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

Working with Angular to add various items to an array based on multiple conditions

Currently, I am a beginner in TypeScript and currently involved in an Angular project. As part of my work, I need to make an API call and perform various operations on the received data: public data_Config: IConfig[] = []; this.getService.Data(input).sub ...

What is the best way to distinguish if users are accessing my Facebook app through an iframe or by directly entering the

If my Twitter app url is http://tw.domain.com/ and the app url is http://apps.twitter.com/demoapp/ I need to ensure that users cannot access the application url directly, they must view it within an iframe on Twitter. What method can I use to detect & ...

What is the best way to transform this functioning JavaScript code into jQuery?

<script type="application/javascript" language="js"> function checkPasswordUpdate(value) { if(value === '1') { var nav = document.getElementById("sNav"); if(document.getElementsByTagName) ...

Arranging numerous items based on date in JavaScript without prior knowledge

I'm facing an issue where I need to showcase JSON data containing events but want them sorted by time. The challenge is that the number of objects in the JSON can vary as users can keep adding more. Below is my code snippet demonstrating how the displ ...

Unexpected output from the MongoDB mapReduce function

Having 100 documents stored in my mongoDB, I am facing the challenge of identifying and grouping possible duplicate records based on different conditions such as first name & last name, email, and mobile phone. To achieve this, I am utilizing mapReduc ...

AngularJS 2 treats lists as custom directives

I am working on developing an e-commerce website. The project involves displaying a list of goods and a basket (which contains selected goods). In order to achieve this, I have created a controller with two arrays: one for goods (already filled) and anothe ...

Is there a way in JQuery to apply the CSS of one element to another selected element?

I'm curious if there is a JQuery function available that can be used to transfer the exact CSS styles from one element to another. I want all the CSS properties to be applied without any additional inheritance. For example: <div id="d1"> &l ...

What is the best way to eliminate the additional square bracket from a JSON file containing multiple arrays?

Seeking JSON data from an array, I encountered an issue with an extra square bracket appearing in the output. After attempting $episode[0] = $podcast->getPodcastByCategoryId($id);, only partial data was retrieved, corresponding to the first iteration. ...

Identifying and handling errors in the outer observable of an RXJS sequence to manage

Encountered a puzzling rxjs issue that has me stumped. Here's the scenario: I have two requests to handle: const obs1$ = this.http.get('route-1') const obs2$ = this.http.get('route-2') If obs1$ throws an error, I want to catch it ...

The Slice method is malfunctioning after the array has been filtered

I am currently working on creating a news portal app using Next JS, Redux, mongoose, and Express. My Issue is: While I am able to filter specific items from an array successfully, I encounter problems when attempting to display a specific number of items, ...

"Rotating the TransformControl in threejs: A step-by-step guide

When the object attached to the transform control rotates, I want the transform control itself to rotate as well. Before the rotation: https://i.sstatic.net/yjTue.png After the rotation: https://i.sstatic.net/2opuU.png As shown in the image, before th ...

Exploring the world of nested JSON serialization and encoding

Struggling with encoding JSON for a project of mine. I have all the necessary values stored in variables but can't seem to get it right. Any assistance would be greatly appreciated. {"id":[{"name":"Test","Class":[{"Grade":"2","id":"34"}]}],"age":"5"} ...

Need help with functions in JavaScript?

I'm struggling with understanding some code related to javascript and angularjs. I came across this line - !function(a,b,c){}(x,y,z) - and I can't make sense of it. It's something new to me and I would appreciate any help in clarifying its p ...

Identifying when several asynchronous JavaScript $.ajax requests have finished

I have a JavaScript function that runs a loop and makes asynchronous AJAX calls. I need to wait for all the AJAX calls to complete before updating the UI. Here is the loop: function sync_SyncLocalStorageToServer() { if (helper_IsAppOnline()) { ...

The array element is not being shown in the id "main" when using a for loop with the onchange function

I've been using document.write to display specific content, but it seems to be removing other elements from the page. Is there a way for me to display this loop inside the element with id="main" without losing any content? When I attempt to use docume ...

Using the ng-show directive in AngularJS allows you to pass elements in

Web Development <li ng-show="sample($event)" TestLi</li> JavaScript Functionality $scope.sample = function($event){ //$event is undefined //perform some action } I have experimented with passing the HTML element using ng-click, but I am curio ...

Sorting prices in descending order using Expedia API

Is there a way to arrange prices in descending order using the response.hotelList[i].lowRate? The provided code is as follows: success: function (response) { var bil = 1; var hotel_size = response.hotelList.length; $('#listD ...

Tips on triggering an AJAX call to load additional content when a user reaches the bottom of the page for the first time

My goal is to dynamically append an HTML file to a div element when the user reaches the bottom of the page. However, I have encountered an issue where the script appends the content multiple times after refreshing the page. It seems like the Boolean varia ...

Acquire the ng-model within a nested ng-repeat using Protractor

How do I access the ng-model within nested ng-repeats using protractor? <div ng-repeat="field in master.linker | orderBy:'country.name'"> <div> <p> {{ field.country_name }} </p> <label ng-repea ...

Could someone review my coding syntax in JavaScript for utilizing indexOf, split, and looping through multiple inputs to paste the splits?

As someone who is self-taught and codes part-time as a hobby, I am currently working on building a JavaScript/jQuery tool. This tool will allow users to copy rows or columns from Excel and paste them into an online HTML form consisting of a grid of <tex ...