`AngularJS Sorting Items by Category`

I'm attempting to showcase a menu categorized by different categories. Each category is represented by the key in an array of menu items, such as "brownies" and "cakes."

This is what I am looking at for reference, but it doesn't seem quite right:

filter list of items when clicking category link

HTML:

<section class="choices">
  <div class="categories">
   <ul>
    <li ng-repeat="menu in fullMenu">
      <a ng-repeat="(key,val) in menu" href="" ng-click="categoryFilters.category = {{key}}">{{key}}
      </a>
    </li>
   </ul>
  </div>

</section>

<section class="category" ng-repeat="menu in fullMenu | filter: categoryFilters">

  <div ng-repeat="items in menu">
   <ul>
    <li ng-repeat="item in items">
      <img src="{{item.image_url}}">
      <h3>{{item.name}}</h3>
      <p>{{item.description}}</p>
      <p><span>$</span>{{item.price}}</p>
    </li>
   </ul>
  </div>

</section>

JS:

  angular.module('bakeryMenuApp')
  .controller('mainCtrl', function($scope, dataService) {  
    dataService.getMenus(function(response) { 
        $scope.fullMenu = response.data.menus;
        $scope.categoryFilters = {}   
    });
  })

JSON:

{  
   "menus":[  
      {  
         "brownies":[  
            {  
               "name":"Baker's Choice Bars Assortment",
               "price":"45",
               "description":"A beautiful and delicious assortment of Magnolia Bakery’s double fudge brownies, chocolate chunk blondies and magic cookie bars.",
               "image_url":"https://pantograph0.goldbely.com/s364/uploads/product_image/image/8346/bakers-choice-bars-assortment.1ddd25a1f59a89a1de2d0583dab50000.jpg",
               "is_vegan":false,
               "is_gluten_free":false
            }
         ]
      },
      {  
         "cakes":[  
            {  
               "name":"Raseberry Lemon Cake",
               "price":"50",
               "description":"Vanilla crème fraîche cake layered with raspberry Swiss meringue buttercream and lemon curd filling, covered with raspberry buttercream.",
               "image_url":"http://www.empirecake.com/_main_site/wp-content/uploads/2014/12/Rasberry_Lemon_01_final_drkr-600.jpg",
               "is_vegan":false,
               "is_gluten_free":false
            }
         ]
      }
   ]
}

Answer №1

the goal can be reached by ensuring the condition is properly validated

Control && Code

var program = angular.module('program', []); 
program.controller('control', function($scope) { 
$scope.specification = ''; 
  $scope.guidelineList = function(value) { 
    $scope.specification = value; 
  } 
  $scope.directives = [{ 
    "cookies": [{ 
      "title": "Baker's Choice Bars Assortment", 
      "cost": "45", 
      "details": "A beautiful and delicious assortment of Magnolia Bakery’s double fudge brownies, chocolate chunk blondies and magic cookie bars.", 
      "link": "https://pantograph0.goldbely.com/s364/uploads/product_image/image/8346/bakers-choice-bars-assortment.1ddd25a1f59a89a1de2d0583dab50000.jpg", 
      "vegan_option": false, 
      "gluten_free": false 
    }] 
  }, {  
    "treats": [ { 
      "title": "Raseberry Lemon Cake",
      "cost": "50",
      "description": "Vanilla crème fraîche cake layered with raspberry Swiss meringue buttercream and lemon curd filling, covered with raspberry buttercream.",
      "link": "http://www.empirecake.com/_main_site/wp-content/uploads/2014/12/Rasberry_Lemon_01_final_drkr-600.jpg",
      "vegan_option": false,
      "gluten_free": false
    }]
  }]
});
form.ng-pristine {
  background-color: lightblue;
}

form.ng-dirty {
  background-color: pink;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="program" ng-controller="control">
  <section class="choices">
    <div class="categories">
      <ul>
        <li ng-repeat="direct in directives">
          <a ng-repeat="(key,val) in direct" href="" ng-click="guidelineList(key)">{{key}}
      </a>
        </li>
      </ul>
    </div>

  </section>
  <section class="specification" ng-repeat="directive in directives">
    <div ng-repeat="(key, items) in directive">
      <ul>
        <li ng-repeat="item in items" ng-show="specification == key">
          <div>
            <img src="{{item.link}}">
            <h3>{{item.title}}</h3>
            <p>{{item.description}}</p>
            <p><span>$</span>{{item.cost}}</p>
          </div>
        </li>
      </ul>
    </div>

Answer №2

To enhance your filtering capabilities, consider implementing a custom filter to sort data by object key and employing a function to assign categories through user clicks.

You can experiment with the following approach:

HTML:

<section class="choices">
    <div class="categories">
      <ul>
        <li ng-repeat="menu in fullMenu">
          <a ng-repeat="(key,val) in menu" href="" ng-click="setFilterCategory(key)">{{key}}
      </a>
        </li>
      </ul>
    </div>
  </section>
  <section class="category" ng-repeat="menu in fullMenu | filter: filterByCategory">
    <div ng-repeat="items in menu">
      <ul>
        <li ng-repeat="item in items">
          <img src="{{item.image_url}}">
          <h3>{{item.name}}</h3>
          <p>{{item.description}}</p>
          <p>
            <span>$</span> {{item.price}}

          </p>
        </li>
      </ul>
    </div>
  </section>

and controller:

  $scope.selectedCategory = '';

  $scope.setFilterCategory = function(value) {
    $scope.selectedCategory = value;
  };

  $scope.filterByCategory = function(item) {
    if ($scope.selectedCategory)
      return $scope.selectedCategory === Object.keys(item)[0];
    else
      return item;
  };

PLUNKER DEMO

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

Error: NODEJS MYSQL Error ER_NO_DB_ERROR - Database not selected

Database Name: students, Table: student_details, Columns: student_id, student_name, student_email, course_id. I am trying to send a POST request on Postman but it is not working. Error: { errorType: 'selected', sqlState: '3D000', ind ...

Error message: The function this.props.getAnimals is not defined in React-Redux

While utilizing react, redux, and thunk to retrieve data from an API, I have encountered an issue. A TypeError is being thrown stating that this.props.getAnimals is not a function\ This error is triggered by the line: this.props.getAnimals(); Up ...

What is the best way to save a token value to a JavaScript file on my local storage

Hello, I am new to Nodejs and have implemented passportjs token-based authentication. When a user logs in, a token is provided for each user. Now, I want to perform certain operations based on the users who have token values. For example, if a user wants t ...

Stopping the papaparse streaming process once a certain number of results have been achieved

Currently, I am utilizing the PapaParse library to parse a large CSV file in chunk mode. During my data validation process, I encountered an issue where I was unable to stop streaming the data once validation failed. I attempted to halt the streaming by ...

React application launches a new tab with an incorrect URL, using "https" instead of "http"

Using the Link component from the react-router-dom package, I am trying to ensure that my semantic-ui-react <Dropdown.Item> opens in a new tab with a specific URL. Initially, the issue was that when clicking on the item, the desired URL would be appe ...

Exploring JSON data with React Native

When I send a JSON request, I receive a response with JSON objects; { "kind": "youtube#searchListResponse", "etag": "zy8y9DkaOiYwKh0aStoEqOU_knU", "nextPageToken": "CBQQAA", "regionCode": "GB", "pageInfo": { "totalResults": 40, "results ...

Is there a smarter approach in Vue.js to selectively add classes?

Within my Vue instance, I have implemented a method that conditionally generates HTML markup based on specific conditions. Although the markup remains the same for each scenario, only different styles are applied. I am curious if there is a more elegant a ...

Rendering a page using React and NextJS with server-side rendering to retrieve and showcase dynamic data

At the moment, I am utilizing client-side rendering on a page that fetches data via an API and then presents this raw data. 'use client' import React, { useState, useEffect } from 'react' import axios from 'axios'; const Sol ...

Using jQuery to create a seamless scrolling experience to both the top of a page and to

I've been looking for solutions on how to add both jQuery scroll to top and scroll to anchors, but haven't found any integrated options. Is it possible to achieve this here? We currently have a jQuery function in place to add a scroll-to-top fea ...

Maximizing the versatility of components with styled-components and React: A comprehensive guide to incorporating variants

Currently, I am a novice programmer working on a personal project using React for the front-end. I am looking to create a Button component with the styled-components package that can be easily reused throughout the app with some variations in size, color, ...

Utilize textarea for dynamically populating an Array using jQuery

(JQUERY) I'm encountering an issue with populating an array from a textarea on my page. I am struggling with the formatting required for the array and how to use "split" to achieve this. Can anyone guide me through the process of populating the array ...

Sleek carousel design with optimal spacing between images

Solving the Issue Utilizing Ken Wheeler's Slick plugin has allowed me to create a carousel on my website. However, I've encountered an issue where the images inside the <a> tag aren't evenly spaced and are even overlapping in some ins ...

Is it possible to retry NTLM Authentication failure in Sails.JS?

Currently, my NodeJS application is built on Sails.JS and uses ntlm-express for NTLM authentication. Everything works smoothly when the authentication is successful. However, when it fails (such as when a Firefox user enters incorrect credentials), ntlm-ex ...

Module or its corresponding type declarations not found in the specified location.ts(2307)

After creating my own npm package at https://www.npmjs.com/package/leon-theme?activeTab=code, I proceeded to set up a basic create-react-app project at https://github.com/leongaban/test-project. In the src/index.tsx file of my react app, I attempted to im ...

Select a single radio button containing values that can change dynamically

<input type="radio" on-click="checkDefaultLanguage" id="checkbox" > [[names(name)]] This custom radio input field contains dynamic values and I am attempting to create a functionality where only one radio button can be selected at a time while dese ...

Changing webpage content without using asynchronous methods once authentication has been completed using Google Firebase

My goal is to create a website where users can sign in with Google by clicking a button, and then be redirected to a new HTML page. However, I am facing an issue where the Google sign-in window pops up briefly and closes immediately, causing the HTML page ...

Developing perforations in three.js

This excerpt was sourced from a discussion on adding holes to rendered shapes in Three.js, as seen at THREEJS: add hole to rendered Shape. Despite trying the provided code, it is still not functioning as expected. The encountered error message reads: t ...

Using Express to request data from Mongo database and only receiving the path

I've been troubleshooting a websocket function that interacts with MongoDB to fetch some data stored in the system using 'get'. const User = require('mongoose'); const express = require('express'); const cal = require(&a ...

How to implement smooth scrolling in Bootstrap 4.1 with Scrollspy integration?

I am currently working on integrating the scrollspy function from bootstrap 4.1 into my navbar and I have successfully implemented it. However, I am facing challenges in adding smooth scrolling to it. Despite extensive research on the web, I have been unab ...

What tips do you have for running complex SQLite queries to find files based on tags?

What Is My Current Project? Currently, I am working on developing a file tagging program using JavaScript with Electron. I have decided to incorporate SQLite into the project for data management. However, I am facing a challenge when it comes to implement ...