How to pass the 2 $index values within nested ng-repeat in AngularJS ?
Last Updated :
25 Jul, 2024
In AngularJS applications, we can create dynamic behavior by passing the $index values within the nested ng-repeat directives. In the application, the $index variable or value is nothing but the index of the current item or the product that is in the ng-repeat loop. We can pass these values using 2 different methods. So in this article, we will see the different approaches to pass the 2 $index values within nested ng-repeat in AngularJS.
Steps for Configuring AngularJS Application
The below steps will be followed to configure the AngularJS Application:
- Create a new folder for the project. We are using the VSCode IDE to execute the command in the integrated terminal of VSCode.
mkdir pass-indexes
cd pass-indexes
- Create the index.html file in the newly created folder, we will have all our logic and styling code in this file. We can also create separate files for HTML, CSS, and JS:
We will explore the above approaches & will understand their implementation through the illustration.
Using ng-init and $parent.$index
In this approach, we have defined the two $index values within the nested ng-repeat and passed those values using the ng-init directive to create the custom variable named "categoryIndex" and the "productIndex". These variables mainly are used to receive the indices of the category and product with the iterations. Here, the $parent.$index is used to mainly access the index which is in the outer 'ng-repeat' directive and $parent refers to the parent scope in AngularJS. Using this approach, we can easily access more than 1 index in the application.
Example: Below is an example that demonstrates passing the 2 $index values within nested ng-repeat in AngularJS using ng-init and $parent.$index.
HTML
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js">
</script>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f7f7f7;
}
.product {
width: 200px;
background-color: #fff;
border: 1px solid #ccc;
padding: 10px;
margin: 10px;
float: left;
border-radius: 5px;
box-shadow: 0 0 5px rgba(0, 0, 0, 0.3);
transition: background-color 0.3s;
}
.product:hover {
background-color: #e0e0e0;
}
h1 {
color: #00a100;
}
h3 {
font-weight: bold;
}
</style>
</head>
<body>
<div ng-controller="myController">
<h1>GeeksforGeeks</h1>
<h3>
Approach 1: Using ng-init and $parent.$index
</h3>
<div ng-repeat="category in productCategories">
<div class="product"
ng-repeat="product in category.products"
ng-init="categoryIndex = $parent.$index;
productIndex = $index">
<h3>Category Index: {{ categoryIndex }},
Product Index: {{ productIndex }}</h3>
<p>
Category {{ categoryIndex }} - {{ category.name }}
</p>
<p>Product: {{ product.name }}</p>
<button ng-click=
"showProductDetails(categoryIndex, productIndex)">
View Details
</button>
</div>
</div>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myController', function ($scope) {
$scope.productCategories = [
{
name: 'Electronics',
products: [
{ name: 'Smartphone' },
{ name: 'Laptop' },
{ name: 'Tablet' }
]
},
{
name: 'Clothing',
products: [
{ name: 'T-shirt' },
{ name: 'Jeans' }
]
}
];
$scope.showProductDetails =
function (categoryIndex, productIndex) {
if ($scope.productCategories[categoryIndex] &&
$scope.productCategories[categoryIndex]
.products[productIndex]) {
alert("Clicked on Category " +
$scope.productCategories[categoryIndex].name +
" and Product "
+ $scope.productCategories[categoryIndex].
products[productIndex].name);
} else {
console.error("Invalid indices or data not found.");
}
};
});
</script>
</body>
</html>
Output:
Using Custom Directive
In this approach, we have defined the custom directive "customCategory" which is used to pass and mainly manage the two $index values that are in the ng-repeat loops. This directive mainly encapsulates the overall structure and the functional behavior of displaying the nested elements. In this directive's template, the $index of the current category and the course is displayed and made available for the "Show Indexes" button. This is been shown when the button is been clicked and the showIndexes function has been triggered in the controller, which passes the category and course indexes in as the arguments.
Example: Below is an example that demonstrates passing the 2 $index values within nested ng-repeat in AngularJS using a custom directive.
HTML
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<meta charset="utf-8">
<title>
AngularJS Nested ng-repeat Example
</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f0f0f0;
margin: 0;
padding: 0;
}
.container {
max-width: 800px;
margin: 0 auto;
padding: 20px;
background-color: #fff;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
border-radius: 5px;
}
h1 {
color: #4CAF50;
}
.category {
margin: 10px 0;
}
.item {
padding: 10px;
background-color: #f9f9f9;
border: 1px solid #ccc;
border-radius: 5px;
}
.nested-item {
padding: 10px;
background-color: #fff;
border: 1px solid #ddd;
border-radius: 5px;
margin: 5px 0;
}
button {
background-color: #4CAF50;
color: #fff;
border: none;
border-radius: 5px;
padding: 5px 10px;
cursor: pointer;
}
</style>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js">
</script>
</head>
<body>
<div ng-controller="MainController" class="container">
<h1>GeeksforGeeks</h1>
<h3>Approach 2: Using Custom Directive</h3>
<button ng-click="addData()">Add Data</button>
<custom-category ng-repeat="data in dataList track by $index"
data="data"
on-show-indexes=
"showIndexes(categoryIndex, courseIndex)">
</custom-category>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('MainController', function ($scope) {
$scope.dataList = [];
$scope.addData = function () {
var nestedList = [];
nestedList.push({
courseTitle: "AngularJS for Beginners",
author: "GFGUser1"
});
nestedList.push({
courseTitle: "Advanced Web Development",
author: "GFGUser2"
});
nestedList.push({
courseTitle: "JavaScript Fundamentals",
author: "GFGUser3"
});
nestedList.push({
courseTitle: "Web Design Principles",
author: "GFGUser4"
});
$scope.dataList.push({
nestedList: nestedList
});
};
$scope.showIndexes =
function (categoryIndex, courseIndex) {
alert(`Category: ${categoryIndex}, Course: ${courseIndex}`);
console.log(`Category: ${categoryIndex}, Course: ${courseIndex}`);
};
});
app.directive('customCategory', function () {
return {
restrict: 'E',
scope: {
data: '=',
onShowIndexes: '&'
},
template: `
<div class="category">
<div class="item" ng-repeat=
"nestedData in data.nestedList
track by ($index + '-' +
$parent.$index + '-' + $id)">
<p>
<strong>
Category: {{ $index + 1 }}
</strong><br>
<strong>
Course Title:
</strong>{{ nestedData.courseTitle }}<br>
<strong>
Author:
</strong> {{ nestedData.author }}
<button ng-click=
"onShowIndexes({categoryIndex: $index + 1,
courseIndex: $parent.$index + 1})">
Show Indexes
</button>
</p>
</div>
</div>
`,
link: function (scope, element, attrs) {
scope.categoryIndex = scope.$parent.$index + 1;
}
};
});
</script>
</body>
</html>
Output:
Similar Reads
Non-linear Components
In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial
JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. JavaScript is an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side : On client sid
11 min read
Web Development
Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Class Diagram | Unified Modeling Language (UML)
A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Spring Boot Tutorial
Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers
React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
HTML Tutorial
HTML stands for HyperText Markup Language. It is the standard language used to create and structure content on the web. It tells the web browser how to display text, links, images, and other forms of multimedia on a webpage. HTML sets up the basic structure of a website, and then CSS and JavaScript
10 min read
JavaScript Interview Questions and Answers
JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
Backpropagation in Neural Network
Backpropagation is also known as "Backward Propagation of Errors" and it is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network. In this article we will explore what
10 min read
Polymorphism in Java
Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read