Angular's ng-repeat allows you to iterate over a collection and

I have 4 different product categories that I want to display in 3 separate sections using AngularJS. Is there a way to repeat ng-repeat based on the product category?

Take a look at my plnkr: http://plnkr.co/edit/XdB2tv03RvYLrUsXFRbw?p=preview

var products = [

  {
    "name": "Item 1",
    "dimension": {
      "height": "4 in",
      "width": "3 in"
    },
    "category": "A"
  }, {
    "name": "Item 2",
    "dimension": {
      "height": "2 in",
      "width": "6 in"
    },
    "category": "B"
  }, {
    "name": "Item 3",
    "dimension": {
      "height": "2 in",
      "width": "3 in"
    },
    "category": "C"
  }, {
    "name": "Item 4",
    "dimension": {
      "height": "5 in",
      "width": "2 in"
    },
    "category": "D"
  }

];

Answer №1

If you want to filter the output based on a specific category 'A', you can use the following code snippet:

ng-repeat="item in output.products | filter:{ category: 'A'}"

Note: It seems like many people searched for the same solution on StackOverflow. Make sure to improve your Google skills, OP!

Note 2: Upon revisiting the question, it appears that you might need a custom filter instead:

app.filter('category', function() {
  return function(items, categories) {
    if (!items || items.length === 0) {
      return [];
    }

    return items.filter(function(item) {
      return categories.indexOf(item.category) > -1;
    });
  };
});

To utilize this custom filter, use the following syntax:

ng-repeat="item in output.products | category:['A', 'B']"

Note 3: Keep in mind that using this custom filter on large arrays may impact performance. Consider pre-filtering the data into smaller subarrays if dealing with huge datasets.

Answer №2

If you want to implement custom grouping in Angular, consider using the angular.filter module.

To create your own map function in the controller:

$scope.group = function(elem){
    if(elem.category == 'C' || elem.category=='D'){
       elem.category = 'C OR D' ;
       return elem;
    }
    else return elem;
}

In the HTML template, implement the following:

<ul ng-repeat="(key, value) in products | map: group | groupBy: 'category'">
  Group name: {{ key }}
  <li ng-repeat="product in value">
     Player: {{ product.name }} 
  </li>
</ul>

Please note that by using this method, you may lose some information about the category of the element when it is grouped as C or D. Another approach provided by LoremIpsum allows for better categorization without loss of data. However, with this solution, you have the flexibility to create custom groups as needed. Check out this JSFiddle example for reference.

Answer №3

Here's an example:

<div class="" ng-repeat="item in output.products | filter: {category:'A'}">
. This code will repeat items with Category A. You can also implement custom filtering based on user-defined functions or different criteria.

Answer №4

One option is to utilize ng.if in this scenario.

To see an example, visit http://example.com/sample

  <div class="" ng-repeat="item in output.products" ng-if='item.category =="A"'>

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

Deactivate certain choices in React Select

Encountering difficulties disabling specific options in a large list within a React Select component. A total of 6,500 options are loaded into the select element. Initially, there were issues with search functionality lagging, but this was resolved by impl ...

Prevent the creation of references to objects passed as function parameters in a separate list

I'm facing an issue with modifying items from an array and adding them to a new list of objects. The problem arises when I make changes to the item in the new list, it also reflects those changes in the original array. It seems like there is some ref ...

Ways to conceal the scroll bar upon the initial loading of a webpage

Recently, I created a single-page website consisting of 4 sections. The client has specific requirements that need to be fulfilled: The scrollbar should not be visible when the page loads. Once the user starts scrolling past the second section, the scrol ...

What is the best way to handle dynamic URLs in Protractor testing?

We have decided to utilize AngularJS for the development of our website, which results in dynamic URL changes. As a result, I find myself needing to adjust the URLs each time they change. How can I successfully verify these dynamic alterations using Prot ...

Clicking on an ID within a jQuery list will return the value

<ul id='myid' > <li>Apple MacBook Pro</li> <li>Apple iPad Pro</li> <li>Apple iPhone 12 Pro</li> <li>Apple Watch Series 6</li> <li>Apple AirPods Pro</li> </ul> ...

Engaging with the crossrider sidepanel extension

When it comes to the crossrider sidepanel, I prefer using an iframe over js-injected html to avoid interference with the rest of the page. However, I am struggling to establish any interaction between my browser extension and the iframe. I believe adding ...

Sending Location Data From JavaScript to PHP via Cookies

I encountered an issue while attempting to send Geolocation coordinates from JavaScript to PHP using Cookies. The error message I am receiving is: Notice: Undefined index: data in /Applications/XAMPP/xamppfiles/htdocs/samepage.php on line 24 The file name ...

The search box output will be the same as the JSON result

I have a server in Node.js that is able to read and process a JSON file containing various data, including unique user IDs. I have incorporated a search box into my HTML page, and I am seeking assistance with creating a jQuery method (which will require AJ ...

Maintaining an onExit function in the ui-router framework

I am trying to implement an animation on an element within a page when the user is transitioning out of a state. Here is my current code snippet: { ....., views: { ... }, onExit: function(){ someEle.classList.remove("someClass"); // ...

"Exploring the challenges of implementing a jquerytools tooltip with AJAX

Currently, I have set up an ajax call to run every 15 seconds. The issue arises when the ajax call disables the tooltip if it's open at that moment for a particular item. This results in the destruction of only the tooltip being displayed, leaving oth ...

What are the steps to create a dynamic navigation bar in React without encountering hydration issues?

My goal is to dynamically show or hide links based on user authorization. Here's my initial approach: const Navbar = () => { const { canDo, ...} = useUser(); //A Zustand store return ( <> <div> <ul> ...

Leveraging composer to enhance the organization of my dependencies

As I organize my files for my PHP-based website, I've turned to composer for assistance. One issue I've encountered is loading front-end dependencies like jquery into my pages, specifically the index.php. In the past, I manually specified each js ...

CSRF validation did not pass. The request has been cancelled. The failure occurred due to either a missing or incorrect CSRF token

Upon hitting the submit button in the login form, I encountered the following error message: Forbidden (403) CSRF verification failed. Request aborted. CSRF token missing or incorrect. settings.py MIDDLEWARE = [ 'django.middleware.security.Secur ...

Show a picture upon hovering the button

Welcome to my website. My goal: Show an image when a user hovers over the links. I must be making some silly error, but I can't pinpoint it. This is what I've attempted so far: HTML <ul class="nm"> <li><a href="#">Cork& ...

Setting up a Node.js http2 server along with an http server specifically designed for a single

In my upcoming project, I am interested in implementing the http2 protocol. My goal is to have both http and http2 servers running on a single domain and port, if feasible. When a client that does not support http2 connects, communication will default to ...

Is there a method to ascertain the relative position of a point on a polygon?

Apologies in advance as I might have a hard time wording this question properly, so I'll start by explaining my objective. I'm currently working with JavaScript and Raphael. My goal is to save the position of a point in relation to the four cor ...

Is there a way to prevent this JavaScript code from deleting the initial row of my table?

Looking at the code provided, it's evident that creating and deleting new rows is a straightforward process. However, there seems to be an issue where the default/origin/first row (A-T) gets deleted along with the rest of the rows. The main requiremen ...

Why does one of the two similar javascript functions work while the other one fails to execute?

As a new Javascript learner, I am struggling to make some basic code work. I managed to successfully test a snippet that changes text color from blue to red to ensure that Javascript is functioning on the page. However, my second code attempt aims to togg ...

Is it possible to swap images by clicking on them?

Let's say I'm working with 3 images. Image A, B and C. A is the main image initially. If I click on image B, it will become the main image and image A will take its place in the old position. The same condition applies when B is the main image a ...

Creating unique URLs for websites can be accomplished by following these steps:

I am in the process of developing a website where content in the main div within the body section can be replaced. However, I have realized that all content will end up on the same URL. Any suggestions on how to fix this? HTML/PHP(index.php): <htm ...