Generate a dynamic list using NG-Repeat with changing classes

Is there a way to print each item that matches the index of the first loop as an li element with different classes?

For instance, having li elements with classes like cat1_li, cat2_li, cat3_li for each respective loop iteration.

I'm struggling with nesting ng-repeats inside each other and can't figure out why all items are being printed in separate lists. It's clear that multiple lists are being created, but I'm unsure how to fix this issue.

If anyone could offer some insight or take a look at my code, I would greatly appreciate it.

Here is the HTML:


    <div>
     <ul class="tasks" ng-repeat="cat in taskCategories.categories">
    {{ cat }}
    <li ng-repeat="tasks in tasklist.tasks | orderBy:'category' | filter: {category: cat}" class="cat{{ index + 1 }}_li">
        <span>
          <span class="panel_title">
          {{ tasks.title }}
          </span>
        </span>
    </li>
</ul>
</div

Object:


app.controller('MainController', ['$scope', function($scope) {


$scope.taskCategories = {
    categories: [
        'work',
        'chores',
        'learning',
        'lifting'
    ]
};

$scope.tasklist = {
    tasks: [{
            title: 'Email Gregory',
            category: 'work'
        }, {
            title: 'Clean the Kitchen',
            category: 'chores'
        }, {
            title: 'AngularJS',
            category: 'learning'
        }, {
            title: 'Hose Car',
            category: 'chores'
        }, {
            title: 'Email Jethro',
            category: 'work'
        }, {
            title: '400 lbs',
            category: 'lifting'
        }
    ]
};
}]);

Answer №1

If you need to access the Category's index within a nested ng-repeat, you can use $parent.$index:

var app = angular.module('app', []);

app.controller('MainController', ['$scope',
  function($scope) {
    $scope.taskCategories = {
      categories: [
        'work',
        'chores',
        'learning',
        'lifting'
      ]
    };

    $scope.tasklist = {
      tasks: [{
        title: 'Email Gregory',
        category: 'work'
      }, {
        title: 'Clean the Kitchen',
        category: 'chores'
      }, {
        title: 'AngularJS',
        category: 'learning'
      }, {
        title: 'Hose Car',
        category: 'chores'
      }, {
        title: 'Email Jethro',
        category: 'work'
      }, {
        title: '400 lbs',
        category: 'lifting'
      }]
    };
  }
]);
.cat1_li {
  background-color: yellow;
}

.cat2_li {
  background-color: cyan;
}

.cat3_li {
  background-color: pink;
}

.cat4_li {
  background-color: lime;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="MainController">
  <ul class="tasks" ng-repeat="cat in taskCategories.categories">
    {{ cat }}
    <li ng-repeat="tasks in tasklist.tasks | orderBy:'category' | filter: {category: cat}" class="cat{{ $parent.$index + 1 }}_li">
      <span>
        <span class="panel_title">
          {{ tasks.title }}
        </span>
      </span>
    </li>
  </ul>
</div>


UPDATE

Based on your feedback, it seems that using only one ng-repeat is more efficient:

var app = angular.module('app', []);

app.controller('MainController', ['$scope',
  function($scope) {
    $scope.taskCategories = {
      categories: [
        'work',
        'chores',
        'learning',
        'lifting'
      ]
    };

    $scope.tasklist = {
      tasks: [{
        title: 'Email Gregory',
        category: 'work'
      }, {
        title: 'Clean the Kitchen',
        category: 'chores'
      }, {
        title: 'AngularJS',
        category: 'learning'
      }, {
        title: 'Hose Car',
        category: 'chores'
      }, {
        title: 'Email Jethro',
        category: 'work'
      }, {
        title: '400 lbs',
        category: 'lifting'
      }]
    };
    
    $scope.mappedTasks = $scope.tasklist.tasks.map(function(task) {
      task.category = $scope.taskCategories.categories.indexOf(task.category);
      return task;
    }).sort(function(a, b) {
      return a.category > b.category;
    });;
    
    console.log($scope.mappedTasks);
  }
]);
.cat1_li {
  background-color: yellow;
}

.cat2_li {
  background-color: cyan;
}

.cat3_li {
  background-color: pink;
}

.cat4_li {
  background-color: lime;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="MainController">
  <ul class="tasks">
    <li ng-repeat="task in mappedTasks" class="cat{{ task.category + 1 }}_li">
      <span>
        <span class="panel_title">
          {{ task.title }}
        </span>
      </span>
    </li>
  </ul>
</div>

Answer №2

When utilizing the ng-repeat directive, a new scope is formed with the provided data, along with an added $index variable within that particular scope.

To leverage the parent scope and access the $index, you can follow this approach:

Example in HTML :

<li ng-repeat="tasks in tasklist.tasks | orderBy:'category' | filter: {category: cat}" class="cat{{ $parent.$index + 1 }}_li">

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

Managing extensive text-based passages or titles within React.js

I'm curious about the most effective way to store lengthy text-based HTML elements like <p>, <h1>, <h2>, <h3> in React.js for optimal semantics. After delving into the realm of react.js documentation, I grasped that we have the ...

Adapting the colors of various elements throughout the entire webpage

My goal is to incorporate color-switch buttons on my webpage. When these buttons are clicked, I want the existing colors to change to different shades. However, my challenge lies in the fact that these colors are used for various elements such as backgro ...

Implementing a NestJs application on a microcomputer like a Raspberry Pi or equivalent device

I'm facing a challenge in trying to find a solution for what seems like a simple task. I am aware that using the Nest CLI, I can utilize the command "nest build" to generate a dist folder containing the production files of my project. However, when I ...

Display sub-objects within Chart.js

I'm currently tackling a project in Ionic 3 where I am utilizing an API that returns a JSON response with nested objects. My goal is to display certain aspects of these objects within a bar graph using chart.js. Unfortunately, I lack experience in ma ...

How can I make a POST request from one Express.js server to another Express.js server?

I am encountering an issue while trying to send a POST request from an ExpressJS server running on port 3000 to another server running on port 4000. Here is the code snippet I used: var post_options = { url: "http://172.28.49.9:4000/quizResponse", ti ...

A guide on seamlessly incorporating FlotJs functionalities into a ReactJs application

Having trouble integrating Flot charts into React due to a '$.plot' is not a function error. Here's the code I'm using: Script tags Index.html <script src="dist/libs/js/jquery.min.js"></script> <script src="dist/libs/js ...

How to write a unit test for a factory in AngularJS using Karma?

Currently, I am developing a basic AngularJS 1.x web application. Here is a breakdown of my project structure: main.js: var app = angular.module('app', []); factory.js app.factory('DataFactory', function(){ var DataService = {}; ...

Refining search outcomes using multiple Multiselect boxes in VueJS

In my Vue component, I have successfully displayed results from a data object and created multiple multiselect boxes. However, I am facing challenges with filtering. I understand how to set and compare a single value from the multiselect for displaying sp ...

Several mistakes occurred involving auth0, react, apollo, babel, and webpack

I seem to be facing some challenges while trying to integrate auth0 into my project. Every time I fix one issue, another one pops up and it's always the same trio of errors: -require is not a function -window is not defined -missing class properties ...

Switch up the Angular base URL using ngx-translate

I successfully integrated ngx-translate into my Angular project. Now, I want to dynamically change the base href based on the language selected from the header menu. Currently, the URL appears as: "localhost:4200". However, upon launching the project, it ...

Adjust the initial scroll position to - apply overflow-x: scroll - on the specified element

I have an image that can be scrolled to the right on screens that do not fit the full width, but I want the center of the image to be displayed first instead of the left side. Below is my React code: import React, { useEffect, useRef, useState } from &qu ...

Get image data from Next.JS API and show it in the web browser

I am looking to utilize my own next.js endpoints to request an image that I can then embed into my website. Currently, the issue I am facing is that the image seems to be immediately downloaded and does not display in the browser window. import type { Next ...

Calculating the hours between a start date and end date in AngularJS while excluding weekends

I'm working on an application that involves a start datetime picker and end datetime picker. Does anyone have suggestions on how to calculate the number of hours between two dates, excluding weekends, using AngularJS? ...

Any ideas on how to extract binary data from PHP passthru using a JavaScript ajax request?

I am facing an issue with retrieving and playing an audio file from a server using JavaScript. The ajax call in my code doesn't seem to callback, and I'm not certain if I'm handling the audio correctly in JavaScript. Below is the PHP file t ...

Access files directly through our convenient file storage site

I'm currently delving into the world of angular JS, and I've come across $https. I was looking to upload a file called db.php which includes: { "vcRecords": [ {"name":"Madison" ,"nickName":"Madilove" ,"coderType":"Injection / Fortre ...

Converting a date from PHP to JavaScript

My PHP code generates the following date: <?php date_default_timezone_set('Europe/London'); echo date('D M d Y H:i:s O'); ?> Additionally, I have a JavaScript/jQuery script that displays this date on the website: setInterval( ...

Issue found in React Js test - TypeError: source.on does not exist as a function

I'm encountering an issue with my post request using multipart/form-data. Everything runs smoothly, except for the tests which are failing. When running the tests, I encounter an error message: TypeError: source.on is not a function. This is the code ...

CombineReducers takes all the reducer content and unpacks it into a single reducer

As I work on developing a small application, I am contemplating the best strategy for organizing reducers within it. My objective is to retrieve JSON data from the application state and structure it as shown below: { "fruits": [ {"appl ...

How can I duplicate or extract all the formatting applied to a specific text selection in Ckeditor?

I am currently utilizing CKEditor version 3.6 within my Asp.net MVC 3 Application. One of my tasks involves creating a Paint format option similar to Google Docs. I am looking to integrate this feature into CKEditor. Is there a way in CKEditor to transfe ...

Transferring an array of objects from one array to another with the click of a button

I'm facing an issue with moving data between two arrays of objects using buttons in a Nextjs project. The functionality works correctly when selecting a single data item, but it gives unexpected results when selecting multiple items. Although my code ...