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

"Having trouble implementing sorting functionality on a click event in a React application with Material-UI table

Default behavior displays data in ascending order. Clicking on the table header should toggle between descending and ascending orders. Load Data in ascending order -> On click, change to descending order -> Again on click, change to ascending -> ...

Incorporating SEO for a Flash-Based Website

After reading through various discussions on this topic, it seems like my question still remains unanswered. We are gearing up to revamp our company's website in the coming months. Currently, our site is mostly text-based, which has helped us achieve ...

Difficulties encountered while attempting to modify a class using Javascript

Recently, I've encountered an issue with my JavaScript where I am unable to keep a particular element's class changed. Despite attempting to change the class to "overlist", it only stays that way briefly before switching back to its original stat ...

Converting milliseconds into a formatted DateTime using AngularJS: A step-by-step guide

Upon receiving JSON data from the server, I obtained a date-time in milliseconds: $scope.JDT = "1492499995056";. While I am able to display the scope variable 'JDT' on my view using a filter: {{JDT | date:"dd/MM/yyyy h:mm:ss a"}} ... I do not a ...

Steps to validate individual input text fields that create a date and display an error message if the date is not valid

Currently, I am working on a React Material UI component designed to capture a user's 'Date of Birth'. This component consists of three separate inputs for the day, month, and year. In order to enhance this functionality, I would like to im ...

What are the steps to fixing the date time issue between NextJS and Firebase?

I am facing an issue with Firebase Database returning timestamps and unable to render them into components using Redux. How can I resolve this error and convert the timestamp to a date or vice versa? I need help with valid type conversion methods. import ...

How can I incorporate any .NET dll into a React Native project?

I have certain .dll files that are crucial for the printer connectivity, api integration, and sql operations. I am eager to incorporate these .dll files into my React Native application, but unfortunately, I have hit a roadblock in terms of importing the ...

Error Encountered: Angular - Despite successful $http.delete request, the operation does not actually take

I am currently facing an issue with deleting a customer in my Angular + PHP application. Although the application returns success without any errors, it fails to delete the customer from the database. Here is the code snippet of my Angular controller: ...

The integration of cypress-cucumber-preprocessor with multiple testing frameworks appears to be experiencing compatibility issues

I am trying to set up a connection between Cypress and Cucumber, and I came across this plugin: https://www.npmjs.com/package/cypress-cucumber-preprocessor However, I am having trouble with my implementation as it seems to be missing. I have also added th ...

JavaScript Radio Buttons

Below are the different radiobuttons: Apple <input type="radio" id="one" name="apple" data-price="10" value="light"/> Light <input type="radio" id="two" name="apple" data-price="20" value="dark" /> Dark <input type="text" id="appleqty" name ...

How come it's not possible to modify the text of this button right when the function kicks off?

When I click a button, it triggers a JavaScript function. The first line of code within the function uses jQuery to change the HTML of the button. However, the button's text does not update in the browser until after the entire function has completed, ...

PostgreSQL dynamic query with Node.js

I am currently developing a note-taking app using REACT. My focus is on tracking only the changes made by the user to the note, rather than the current state of the note. For properties that have not been altered, I intend to send them as an empty string ...

What is the best method for calculating the total sum by multiplying the values in an array?

In my current project, I have an array consisting of multiple objects, each containing a property named "amount". My goal is to sum up all these amount values to get the total. Initially, I attempted to use a for loop but encountered an issue where settin ...

inSession variable in express: set to false

i keep receiving inSession:false when attempting to log in, it is expected to return true. I am utilizing express session, in combination with postges and sequalize. I have logged the state values and they are being rendered correctly, so they are n ...

Troubles with modal functionality in Ionic application involving ion-slide-box

Utilizing ion-slider to display images has been a seamless experience, except for one hiccup. If I navigate directly from the first full image back to the home screen, the slider ceases to function properly. To address this challenge, I have employed spec ...

Populate a JSON table in React with checkboxes and automatically mark them based on the JSON data

I'm currently working on creating a React table using JSON data like this: [ { "Id_side": 123, "Name_side": "R4", "Name_cycle": "C1" }, { "Id_side": 345, "Name_side": "M1", "Name_cycle": "C2" ...

Tips for resolving an error in PHP and MYSQL code where data is being selected from the incorrect table in the database

I am working on a PHP code with MYSQL. It involves selecting data from the database using a dropdown list with AJAX and displaying the results on the screen. I have three dropdown lists that are dependent on each other and each dropdown has its own table t ...

How can I refresh the GUI in AngularJS after a Promise resolves?

My perspective is linked to a group of objects that display flawlessly. Among these objects, there is an async property that, upon completion, fails to update its value in the user interface. To trigger the asynchronous process, I iterate through each prop ...

Encountering the WRONG_DOCUMENT_ERR: DOM Exception 4 error when attempting to close Fancybox after making edits in inline Tiny

I am encountering a problem with my fancybox that includes a form for collecting user input, which features a tinyMCE editor. When trying to close the fancybox after making substantial edits in the TinyMCE, whether by clicking the close X or submitting the ...

Determining which data is retrieved from a database based on a specific field using Sequelize and MySQL

I'm looking to retrieve the most recent records from a database, organized by category. My goal is to fetch 20 records, with 5 of the latest posts in each category. I want to ensure that the result consists of 20 total records, evenly distributed amon ...