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
How to iterate over the keys and values with ng-repeat in AngularJS ? The task is to iterate over a JS object (its keys and values) using the ng-repeat directive. This can be done using parenthesis in the ng-repeat directive to explicitly ask for a key-value pair parameter from angularJS. Here the variable key contains the key of the object and value contains the valu
3 min read
How to iterate over the keys and values with ng-repeat in AngularJS ? The task is to iterate over a JS object (its keys and values) using the ng-repeat directive. This can be done using parenthesis in the ng-repeat directive to explicitly ask for a key-value pair parameter from angularJS. Here the variable key contains the key of the object and value contains the valu
3 min read
How To Display Values With Interpolation In Angular? Angular is a powerful framework for building dynamic web applications. One of its key features is data binding, which allows developers to display and update values seamlessly within the UI. Interpolation is a fundamental technique in Angular that enables the integration of component data directly i
3 min read
How to fetch the details using ng-repeat in AngularJS ? In this article, we will see how to fetch the details with the help of the ng-repeat directive in Angular, along with understanding its implementation through the illustrations. AngularJS contains various types of pre-defined Directives, where most of the directives start with ng which denotes Angul
2 min read
How to fetch the details using ng-repeat in AngularJS ? In this article, we will see how to fetch the details with the help of the ng-repeat directive in Angular, along with understanding its implementation through the illustrations. AngularJS contains various types of pre-defined Directives, where most of the directives start with ng which denotes Angul
2 min read
How to access index of the parent ng-repeat from child ng-repeat in AngularJS ? In this article, we will see How to access the index of the parent ng-repeat from child ng-repeat in AngularJS.In AngularJS applications, when we implement the nested ng-repeat directives and if we need to access the index of the parent ng-repeat from the child ng-repeat, then we can do this by usin
5 min read