AngularJS offers a convenient way for developers to fetch subcategories based on categories

Here is the JSON data provided for reference.

JSON Data

{
"1":{"id":"1","name":"Websites IT & Software","sub_cat":[
    {"id":"1","name":"Build a Website","description":"Build a Website"},
    {"id":"2","name":"Build an Online Store","description":"Build an Online Store"},
    {"id":"3","name":"Get Traffic to my Website ","description":"Get Traffic to my Website "},
    {"id":"4","name":"Write some Software","description":"Write some Software"},
    {"id":"5","name":"Convert a Template to a Website","description":"Convert a Template to a Website"},
    {"id":"53","name":"Create a Wordpress Template","description":"Create a Wordpress Template"},
    {"id":"54","name":"Create a Joomla Template","description":"Create a Joomla Template"},
    {"id":"55","name":"Create a Drupal Template","description":"Create a Drupal Template"},
    {"id":"56","name":"Develop a Mac Application","description":"Develop a Mac Application"}
    ]},
"2":{"id":"2","name":"Mobile","sub_cat":[
    {"id":"6","name":"Write an iPhone application","description":"Write an iPhone application"},
    {"id":"7","name":"Write an iPad application","description":"Write an iPad application"},
    {"id":"8","name":"Write a Blackberry application","description":"Write a Blackberry application"},
    {"id":"9","name":"Write an Android application","description":"Write an Android application"},
    {"id":"57","name":"Create a Mobile Website","description":"Create a Mobile Website"}]}}

I am looking to retrieve subcategories based on the selected category in an Angular-friendly manner. Would it be necessary to use Ajax calls again to fetch subcategories based on the chosen category?

If you have any insights or suggestions on how I can achieve this, your help would be greatly appreciated. Thank you :)

Answer №1

To begin, it is necessary to eliminate the keys "1" and "2" from your object and instead create an array of objects structured like this:

$scope.categories = [{
      "id": "1",
      "name": "Websites IT & Software",
      "sub_cat": [{
        "id": "1",
        "name": "Build a Website",
        "description": "Build a Website"
      }, {
        "id": "2",
        "name": "Build an Online Store",
        "description": "Build an Online Store"
      }]
    },
    {
      "id": "2",
      "name": "Mobile",
      "sub_cat": [{
        "id": "6",
        "name": "Write an iPhone application",
        "description": "Write an iPhone application"
      }, {
        "id": "7",
        "name": "Write an iPad application",
        "description": "Write an iPad application"
      }]
    }];

Next, you will need to utilize the ng-options and ng-repeat directives for displaying all the necessary information. Here is an example:

<select ng-options="item as item.name for item in categories" ng-model="selectedCategory">
</select>

    <table class="table">
      <thead><tr>
          <th>ID</th>
          <th>Name</th>
          <th>Description</th>
      </tr></thead>
      <tbody>
        <tr ng-repeat="subCategory in selectedCategory.sub_cat">
          <td>{{subCategory.id}}</td>
          <td>{{subCategory.name}}</td>
          <td>{{subCategory.description}}</td>
        </tr>
      </tbody>
    </table>


View the Plunkr here: http://plnkr.co/edit/me0vis?p=preview

Answer №2

If you're looking to enhance your JavaScript code with additional functionality, consider utilizing a third-party library like underscore.js. This library offers a variety of useful functions, such as "where":

_.where(list, properties) This function iterates through each value in the list and returns an array of values that match all of the key-value pairs specified in the properties object.

_.where(listOfPlays, {author: "Shakespeare", year: 1611}); => [{title: "Cymbeline", author: "Shakespeare", year: 1611}, {title: "The Tempest", author: "Shakespeare", year: 1611}]

To learn more about this library and its capabilities, visit http://underscorejs.org/#where

For alternative options, you can also explore lodash at https://lodash.com/

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

How can I create an efficient AngularJS application with minimal NPM dependencies?

Currently, as I develop my AngularJS app, I am utilizing npm to download all necessary JS dependencies. These dependencies are stored within the node_modules folder of my application, and everything is running smoothly. However, when it comes time to deli ...

How can I define an HTML array in PHP when it shows an "Undefined Index" error?

Hey there, I have a quick question about PHP that I've been learning. In the code snippet below, why is $html[$firstname] showing up as an undefined index in the server error logs? Any quick help would be greatly appreciated. Here's the full cod ...

What is the process for integrating npm packages with bower?

Currently, I am immersing myself in the realm of ember using a grunt/bower workflow. I have noticed that a lot of the ember extensions are available on github as npm packages. Can anyone provide guidance on the most effective approach for incorporating th ...

Attempting to utilize console.log to print the ID using jQuery

I'm having trouble retrieving the id from a div tag and logging it to the console, as it returns undefined. Any thoughts on why this might be happening? <?php $id = get_the_ID(); ?> <div class="about-cont" id="<?php echo $id ?>">< ...

Error message shown in Chrome Extension: "jQuery is not defined" may occasionally occur

When the user clicks on the browserAction icon of my extension, I am loading a code programmatically. However, sometimes it works and other times I encounter the error "jQuery is not defined". Here is the snippet of my code: var injectElementLoaded = fal ...

Create specification for the properties of the child component

I am interested in working with the props of a parent element's children and validating those props. Can I achieve this using prop-types? export default function MyComponent(props) { return ( <div> {React.Children.map(props.chil ...

What is the best way to extract a specific field from a JSON response string?

I have a response sample with the following structure: A = [{ user: { score_level: 16, is_system: false, location: 'Mumbai', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e1808382a199989bcf8e9 ...

There seems to be an issue with populating the JSON data

Currently, I am attempting to develop a Facebook Feed application for iOS. My approach involves utilizing the JSON framework, but unfortunately, I'm encountering some challenges. Each time I execute my code, an error message is displayed "* Terminatin ...

You cannot use a relative path when inserting an image tag in React

I am having an issue with my img tag not loading the desired image when using a relative src path in my React project. When I try: //import { ReactComponent } from '*.svg'; import React from 'react'; import firebase from "./firebas ...

"Adding the Whats app share button underneath your Blogger post: A step-by-step guide

Can you help me with adding a Whats App share button below my post? Here is the CSS code on my website: .tl-postShare{text-align:right;} .tl-postShare ul{display:inline-block;} .tl-postShare ul li{margin:0;} .tl-tagnShare{position:relative;overflow:hidde ...

Tips for resolving the issue of "Warning: validateDOMNesting(...): <div> cannot be a child of <tbody>"

Users list is passed as a prop to the UserItem Component in order to iterate over the user list and display them on a table. The list is being displayed correctly, and there are no divs in the render return, but an error persists: tried many solutions fou ...

Instructions on incorporating a logical condition for an object that is entering a region in motion

I am currently in the process of developing a new game concept. The goal of the game is to maneuver a square across the screen while avoiding raindrops that fall from the top of the canvas. I need assistance with programming the logic so that when a rain ...

Looking for a drag-and-drop solution using Vanilla Javascript, no need for jQuery

Looking for assistance with creating a click-and-drag solution for a background image using Vanilla Javascript. I came across a jQuery solution on Codepen, but I need help translating it into Vanilla Javascript. Draggable.create(".box", { ...

Extracting information from JSON using jQuery

this is a sample json object: { "box 1": [{ "difficulty_grade": "5a+" }, { "gym": "New_gym" }, { "route_author": "some author" },]} https://i.sstatic.net/UJodJ.png Here is the code snippet: variable groups contains JSON data as shown in the ...

Strip the brackets from PHP JSON output to be compatible with Android Java code

Here is the PHP code I am using: $userdetails = mysqli_query($con, "SELECT *FROM aircraft_status"); #$row = mysql_fetch_row($userdetails) ; while($rows=mysqli_fetch_array($userdetails)){ $status[]= array($rows['Aircraft']=>$rows['Stat ...

Sending a document through the input field with React Hook Form

In my application, I have implemented a file input to submit a file and send it to a firebase storage bucket. To achieve this functionality, I am utilizing the react-hook-form library. However, I encountered an issue - I wanted the file to be uploaded with ...

Steps for Implementing a "Load More" Button on an HTML JSON Page

I'm currently engaged in a project that involves fetching product information from a JSON file and displaying it on an HTML page using JavaScript. While I've successfully implemented the fetch function, I now want to add a "Load More" function/bu ...

What is the reason behind GSON interpreting both " " and "\n" as line breaks?

Here is a code snippet I have: public static void main(String[] args) { String key = "myjsonkey"; String baseJson = "{\"" + key + "\":\"my json %svalue\"}"; String inBackslashAndN = String.format(baseJson, "\\n") ...

What is the best way to allow CORS in an internet server by utilizing AJAX and PHP in order to obtain a font to be used on a different BigCart

Currently, I am using BigCartel for website design. I am looking to incorporate a custom font into my design. However, regardless of the server I use (currently a free Hostinger server), I am unable to enable CORS using htaccess. Recently added to .htacc ...

TinyMCE version 5.x - Stand out with a specific selection in a personalized drop-down navigation bar

In my customized TinyMCE 5.x dropdown menu, there are 3 options that adjust the width of the editor. I am looking for a way to indicate the currently selected option, but I am unable to interact with the menu items once they are initialized. It seems like ...