Create a list using ng-repeat in AngularJS, each item separated by "custom categories"

I am looking to create a dynamic list that will display values entered by users, categorized by custom categories. The challenge is that I do not know in advance which category each element will belong to. Here's an example of how I envision the list being displayed:

Category 1:
- Element 1
- Element 2
- Element 3

Category 2:
- Element 1
- Element 2
- Element 3

My Custom Category:
- Element 1
- Element 2

I attempted to use an ng-repeat along with filtering to avoid duplicate categories. The idea was to first display the category titles and then show the corresponding elements beneath each title using another ng-repeat with an ng-if statement to filter based on the category:

<div ng-repeat="x in elements | unique:'Category'">
     <h2>{{x.Category}}</h2>
     <div class="element" ng-repeat="y in elements" ng-if="y.Category === {{x.Category}}">
        <p class="click-text">{{y.Title}}</p>
     </div>
</div>

This setup is quite messy and I need assistance in finding a cleaner solution.


Here is an example JSON array of elements:

[{
  "Category": "Category 1",
  "Title": "Title example",
  "Comments": "Example comments"
},
{
  "Category": "Category 1",
  "Title": "My cat is named George",
  "Comments": "Example comments"
},
{
  "Category": "Category 1",
  "Title": "Hocus pokus",
  "Comments": "Example comments"
},
{
  "Category": "Category 2",
  "Title": "7 projects going LIVE now",
  "Comments": "Example comments"
},
{
  "Category": "Category 2",
  "Title": "Batman vs Superman was a good movie",
  "Comments": "Example comments"
},
{
  "Category": "Category 2",
  "Title": "projects (more)",
  "Comments": "Example comments"
},
{
  "Category": "Custom Category",
  "Title": "Remember, remember the fifth of november",
  "Comments": "Hello there!"
},
{
  "Category": "Custom Category",
  "Title": "It's night, electric night",
  "Comments": "General Kenobi"
}]

Answer №1

If you want to organize elements by category and iterate through them based on object properties, you can do so by creating an object with categories and their corresponding elements. For a detailed guide on iterating over object properties, refer to the ngRepeat documentation.

Whenever you add a new element, make sure to include it in the object as well, placing it next to other elements within the same category.

Below is a demonstration of this concept in action (take note of how the mapping from categories to elements is established within the vm.init function):

angular
  .module('elementsApp', [])
  .controller('elements', function() {
    var vm = this;
    vm.elements = [{
        "Category": "Category 1",
        "Title": "Title example",
        "Comments": "Example comments"
      },
      {
        "Category": "Category 1",
        "Title": "My cat is named George",
        "Comments": "Example comments"
      },
      {
        "Category": "Category 1",
        "Title": "Hocus pokus",
        "Comments": "Example comments"
      },
      {
        "Category": "Category 2",
        "Title": "7 projects going LIVE now",
        "Comments": "Example comments"
      },
      {
        "Category": "Category 2",
        "Title": "Batman vs Superman was a good movie",
        "Comments": "Example comments"
      },
      {
        "Category": "Category 2",
        "Title": "projects (more)",
        "Comments": "Example comments"
      },
      {
        "Category": "Category invented by me",
        "Title": "Remember, remember the fifth of november",
        "Comments": "Hello there!"
      },
      {
        "Category": "Category invented by me",
        "Title": "It's night, electric night",
        "Comments": "General Kenobi"
      }
    ];
    vm.newElement = {};
    vm.elementGroups = {};

    vm.addElement = function(e) {
      vm.elements.push(e);
      vm.elementGroups[e.Category] = vm.elementGroups[e.Category] || [];
      vm.elementGroups[e.Category].push(e);
      vm.newElement = {};
    };

    vm.init = function() {
      vm.elements.forEach(e => {
        vm.elementGroups[e.Category] = vm.elementGroups[e.Category] || [];
        vm.elementGroups[e.Category].push(e);
      });
    };


  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>

<div ng-app="elementsApp">
  <div ng-controller="elements as ctrl" ng-init="ctrl.init()">
    <form ng-submit='ctrl.addElement(ctrl.newElement)'>
      <input ng-model="ctrl.newElement.Title" placeholder='Title' required>
      <input ng-model="ctrl.newElement.Category" placeholder='Category' required>
      <button type='submit'>Add</button>
    </form>

    <div ng-repeat="(category, elements) in ctrl.elementGroups">
      <h2>{{category}}</h2>
      <div ng-repeat="element in elements">
        {{element.Title}}
      </div>
    </div>
  </div>
</div>

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

Is there a way to set a custom width or make the description responsive?

Is there a way to ensure that the description is responsive and automatically goes to the next line instead of extending horizontally? Although using textField could fix this issue, I also need to adjust the padding and outline. Are there any alternative s ...

Exploring AngularJS and Jasmine: Testing a controller function that interacts with a service via $http

I encountered an issue while testing a controller that relies on a service. The problem arises because the service is currently set to null in order to focus solely on testing the controller. The current test setup is failing due to the BoardService being ...

Ways to guide users through a single-page website using the URL bar

I currently have a one-page website with links like <a href="#block1">link1</a>. When clicked, the browser address bar displays site.com/#block1 I am looking to modify this so that the browser shows site.com/block1, and when the link is clicke ...

Tips for combining or adding duplicated values in a Javascript array

I am facing a problem with an array object that looks like this: [ {"item_id":1,"name":"DOTA 2 Backpack","image":"XXX","qty":1,"original_price":1450000,"total_price":1450000}, {"item_id":2,"name":"Mobile Legend Backpack","image":"XXX","qty":1,"origin ...

Is there a way to call and update an Angular controller's $scope from external sources?

function in controller: $scope.updateData = function () { Words.fetch('update', $scope.randNum) .error(function (data) { console.log('update error: ' + data.message); }) ...

Click and Rotate for More Information

Hello everyone, I have a question regarding creating a unique Tumblr theme. My goal is to make the posts rotate on the y-axis when clicked, revealing like and reblog information. Currently, I've been able to achieve this effect on hover by using code ...

AngularJS, Apache Tomcat, and hashtag URLs

I feel like I'm stuck in a nightmare trying to figure out how to work with Tomcat Apache. My Goal One issue I've encountered in AngularJs is the # problem like www.example.com/#/aboutus After doing some research, I discovered that $locatio ...

Angular Alert: [$injector:modulerr] Unable to create the angularCharts module because: Error: [$injector:nomod]

Although this question has been asked multiple times, the standard solutions provided did not resolve my issue. Therefore, I am sharing my code along with the error in hopes that it will be self-explanatory. Error: Uncaught Error: [$injector:modulerr] Fa ...

AngularJS calling MVC4 Web API not binding models properly

I have a method called Get that accepts a MemberSearchModel parameter from the URI. public List<Member> Get([FromUri]MemberSearchModel searchModel) The MemberSearchModel class has two properties: SearchBy and SearchValue. public class MemberSearch ...

Using the mouse scroll to activate the $anchorScroll effect in Angular instead of a click

I have been searching for a solution to my problem without any luck so far. Hopefully, someone here can provide guidance and help me find a solution. My goal is to replicate the behavior shown in the second example on the following page: https://docs.angu ...

Am I on the right track in my understanding of how document and viewport relate to mouse position in JavaScript?

After reviewing responses from a previous inquiry, it is evident that both pertain to the x and y coordinates of mouse positions. In relation to the document and In relation to the viewport. I have delved into an article on QuirksMode, yet I feel ther ...

Seeking a solution for inserting input values into a JSON file within a node.js environment

As I was developing my new project, a to-do list web application, Below is the code snippet from 'todo.html' : <html> <head> <title>My TODO List</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery ...

Unable to fetch information from Grid to a new window with Form in Extjs 4

Having trouble transferring data from a grid to a form in Extjs 4. I'm attempting to pass the field vid to the form for testing purposes, but I'm unable to do so. Despite trying several examples and ideas, I can't seem to make it work. The ...

The event.preventDefault() method does not work on Android tablets when using touchstart

I have implemented a responsive drop-down menu that involves canceling the click event for tablet users in order to display the sub-menu using event.preventDefault(). This function works perfectly on iPad devices but seems to be ineffective on Android. E ...

The PhpStorm/JavaScript expression statement doesn't involve assignment or function call

I am striving to enhance the cleanliness of my method. Based on the value of an integer number, I am generating different date formats, resulting in the following: getRanges() { var currentDate = new Date(); //This can ...

Is locking Node and npm versions necessary for frontend framework projects?

Currently working on frontend projects in React and Vue, I am using specific versions of node and npm. However, with other developers contributing to the repository, how can we ensure that they also use the same versions to create consistent js bundles? ...

Exploring AngularJS JSON Parsing Techniques (such as utilizing ng-repeat)

My approach to processing json data looks like this: $scope.activities = response.data; console.log($scope.activities.length); var list = []; for (var i = 0; i < $scope.activities.length; i++) { console.log($scope.activities[i].name); list.pus ...

Utilize API to import sunrise and sunset times based on specific coordinates directly into a Google Sheet

After countless hours of trying to crack this code, I’m faced with a final hurdle. The challenge lies in parsing the output from the and storing either the sunrise or sunset time into a variable that can be exported as a result in a Google Sheet. The u ...

How can I arrange an array of strings with dates in C# or use ordering functionality in AngularJS?

I've got an array of dates in the following format: string[] arr=["08.02.2017","09.02.2017","30.01.2017","31.01.2017"] What is the most efficient method to sort this array in C# so that the order is descending? I want the data to be displayed within ...

Why Bootstrap 4 collapse feature is not functioning correctly within a ReactJS map component?

I am currently working on a project that requires implementing a collapse feature. The idea is to display all available content when the user clicks the Read More button (which is functioning as intended for collapsing). However, I am facing an issue where ...