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

Error occurs when attempting to change the color of a dynamically generated div, resulting in the message: "Type Error: Unable to assign a value to the property '

I'm facing an issue with my code where I have a parent div that loads with a random color, and upon clicking a button, it should create a new colored div inside. However, I keep encountering the following error: TypeError: Cannot set property ' ...

What is the purpose of the Express 4 namespace parameter?

Having worked extensively with Express 4, I recently attempted to implement a namespaced route with a parameter. This would involve routes like: /:username/shows /:username/shows/:showname/episodes I figured this scenario was ideal for express namespacin ...

What is the process for creating an if statement for product activation?

<form method="get" formenctype="text/plain" action="https://app.cryptolens.io/api/key/Activate" > <input type="text" maxlength="23" size="80" name="Key" placeholder="XXXXX-XXXXX-XXXXX-XXXXX" /> <input type="hidden" name="toke ...

The Concept of Interface Segregation Principle within jQuery

Could someone provide a clear explanation of how this function operates using jQuery? Especially in reference to the response found here. It seems similar to the Single Responsibility Principle (SRP) in Object-Oriented Programming. What sets it apart? ...

A guide to resolving cross-origin resource sharing issues using a reverse proxy

After creating a JavaScript web application for processing documents, I am now looking to integrate with web services like NLTK-server, TIKA-server, and SOLR for further analysis. While I can successfully access the REST endpoints of these services using c ...

Using Typescript to replicate Object.defineProperties

Is there a way to emulate Object.defineProperties from JavaScript in Typescript? I am interested in achieving something similar using the syntax of Typescript: Object.defineProperties(someObject.prototype, { property: {get: function() { return v ...

Is it possible to enable sorting for every column in the b-table component?

After reviewing the information on sorting per column in the bootstrap-vue documentation, I am curious if it is possible to enable sorting for the entire table. ...

Tips for securing a navbar in material ui

https://i.stack.imgur.com/CYfmQ.png In my current React project, I am facing an issue with aligning components within the Material-UI AppBar Component. My aim is to achieve a seamless and perfectly straight alignment for three key elements: a logo image, ...

Issues with Braintree webhooks and CSRF protection causing malfunction

I have successfully set up recurring payments with Braintree and everything is functioning properly. Below is an example of my code: app.post("/create_customer", function (req, res) { var customerRequest = { firstName: req.body.first_name, lastN ...

What is the best way to transition a connected component from a class-based to a functional component in TypeScript?

I'm in the process of switching from a class-based component to a functional component. This is a connected component that uses mapState. Here is my initial setup: import { connect } from 'react-redux' import { fetchArticles } from '. ...

Unveiling the Truth about Svelte Transitions

Recently, I attempted to incorporate the guidance provided in this repl () for implementing flying and fading effects on divs. However, it seems that I may have a slight misunderstanding regarding the concept... To tackle this, I designed a component rese ...

Implement a fadeout effect by using a timeout function that adds a class to the div element in

I implemented a loader on my webpage that animates for 3 seconds before a function kicks in to modify the styles and make it invisible. I am looking to add a fadeout effect when the 'waa' style is applied to the 'load' div. setTimeou ...

Combining Mocha, BlanketJS, and RequireJS has resulted in the error message "No method 'reporter'."

While using Mocha with RequireJS, my tests are running smoothly. However, I encountered an issue when trying to incorporate blanket code coverage. The error Uncaught TypeError: Object #<HTMLDivElement> has no method 'reporter' keeps popping ...

What is the best way to integrate a Vue component into a Knockout application?

My webpage is filled with knockout code, but I'm hoping to integrate a Vue.js component for a specific section. I attempted using controlsDescendantBindings on a surrounding tag for the Vue component, and it seems to be partially functional (I tried ...

evaluation of three variables using short-circuit logic

I was quite surprised by the outcome of the code I wrote. It seemed like it wouldn't work because it was checking if something is not running and the ID matches a specific one, then executing the code regardless of the break size limit: if(!isRunning ...

Colorful D3.js heatmap display

Hello, I am currently working on incorporating a color scale into my heat map using the d3.schemeRdYlBu color scheme. However, I am facing challenges in getting it to work properly as it only displays black at the moment. While I have also implemented a ...

Obtaining a Variable Element through Selector

When working with Puppeteer, I am faced with the challenge of clicking on a web button that has a dynamic id like: #product-6852370-Size. Typically, I would use the following code: page.click('#product-6852370-Size'); However, the number withi ...

How to use AngularJS to collapse various panels with unique content

Hey everyone, I'm working on developing a collapsible panel using Angular. The panel should consist of a header and body to display the content. The desired behavior is that when a button is clicked, the content collapses down, and clicking the same b ...

Exploring Methods for Retrieving offsetHeight and scrollHeight in AngularJS

I am currently developing a directive that requires three specific values: scrollTop offsetHeight scrollHeight projectModule.directive('scroller', function ($window) { return { restrict: 'A', link: function (scope, elem, attrs) { ...

Tips for choosing all elements in a form that have a specific class assigned

I am attempting to target all fields in a form with a specific class name and then select all the remaining fields. This is my form: <form style="margin:20px 0" id="myform_2"> <p> Query Name : <input i ...