How to access index of the parent ng-repeat from child ng-repeat in AngularJS ?
Last Updated :
30 Jul, 2024
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 using 2 different approaches like by using the $parent.$index and $index Properties or By implementing the Function in the Controller. This allows us to reference the index of the outer loop in your child loop for various purposes, such as displaying data or implementing conditional logic based on the parent index.
The below steps will be followed to configure the Angular Application in order to access the Index of Parent ng-repeat from child ng-repeat:
Step 1: Create a new folder for the project. We are using the VSCode IDE to execute the command in the integrated terminal of VSCode.
mkdir parent-index
cd parent-index
Step 2: Create the index.html file in the newly created folder, we will have all our logic and styling code in this file.
We will understand the above approaches with the help of suitable illustration.
Using $parent.$index and $index Properties
In this example, we use the $parent.$index and $index properties to access the index of the parent ng-repeat from within the child ng-repeat. The code describes a nested structure where programming topics are listed as parent elements, and each topic contains child posts. By utilizing the $index in both the parent and child ng-repeat directives, we can display and access the respective indices. The "Show Parent Index" button calls a function that sets the showIndex flag to display the indices, and it also records and displays the parent and child indices when the button is clicked.
Example: Below is an example that demonstrates access to the Index of Parent ng-repeat from child ng-repeat in AngularJS Applications using $parent.$index and $index Properties.
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>
.user-container {
border: 1px solid #ddd;
padding: 10px;
margin-bottom: 20px;
background-color: #f9f9f9;
}
.user-header {
font-size: 18px;
font-weight: bold;
color: #333;
}
.index-display {
font-size: 16px;
font-weight: bold;
color: #0073e6;
margin: 10px 0;
}
.approach-title {
color: #000000;
}
.post-container {
margin: 5px 0;
}
.post-content {
display: inline-block;
margin-right: 10px;
color: #444;
}
.show-index-btn {
background-color: #0073e6;
color: #fff;
border: none;
padding: 5px 10px;
cursor: pointer;
font-size: 14px;
border-radius: 5px;
}
.show-index-btn:hover {
background-color: #005aa8;
}
</style>
</head>
<body ng-controller="MainCtrl">
<div style="text-align: center;">
<h1 style="color: green;">
GeeksforGeeks
</h1>
<h3 class="approach-title">
Approach 1: Using $parent.$index
and $index Properties
</h3>
</div>
<div style="margin: 20px;">
<div ng-repeat="topic in programmingTopics"
class="user-container">
<p class="user-header">
Parent ng-repeat:
Topic {{ $index + 1 }}: {{ topic.name }}
</p>
<p class="index-display">
Parent Index: {{ $index }}
</p>
<ul>
<li ng-repeat="post in topic.posts"
class="post-container">
<span class="post-content">
Child ng-repeat: Article
{{ $index + 1 }} by GeeksforGeeks
</span>
<button ng-click="showParentIndex($parent.$index, $index)"
class="show-index-btn">
Show Parent Index
</button>
</li>
</ul>
</div>
</div>
<div ng-show="showIndex"
style="text-align: center;">
<p class="index-display">
Parent Index: {{ parentIndex }},
hild Index: {{ childIndex }}
</p>
</div>
</body>
<script>
var app = angular.module('myApp', []);
app.controller('MainCtrl', function ($scope) {
$scope.programmingTopics = [
{
name: 'JavaScript',
posts: ['Introduction to JavaScript',
'JavaScript Functions',
'JavaScript Arrays']
},
{
name: 'Python',
posts: ['Getting Started with Python',
'Python Lists',
'Python Functions']
}
];
$scope.showParentIndex = function (parentIndex, childIndex) {
$scope.showIndex = true;
$scope.parentIndex = parentIndex;
$scope.childIndex = childIndex;
console.log("Parent Index:", parentIndex,
"Child Index:", childIndex);
};
});
</script>
</html>
Output:
Using a Function in the Controller
In this approach, we access the index of the parent ng-repeat from within the child ng-repeat in AngularJS, a function defined within the controller is used. The code describes a dynamic task management system, where users can add, remove, and display tasks. The showIndex function takes both the user and task as parameters, and it calculates the parent (user) and child (task) indices using the indexOf method. By accessing the user's array, it finds the index of the current user and then, within that user's tasks, determines the index of the specific task.
Example: Below is an example that demonstrates access to the Index of Parent ng-repeat from child ng-repeat in AngularJS Applications using a Function in the Controller.
HTML
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<style>
.user-container {
border: 2px solid #333;
padding: 10px;
margin: 10px;
width: 80%;
background-color: #f0f0f0;
}
.item {
display: flex;
align-items: center;
margin: 5px 0;
}
.show-index-btn {
background-color: #007bff;
color: #fff;
border: none;
margin-left: 10px;
cursor: pointer;
}
.remove-item-btn {
background-color: #dc3545;
color: #fff;
border: none;
margin-left: 10px;
cursor: pointer;
}
.add-item-btn {
background-color: #28a745;
color: #fff;
border: none;
margin-top: 10px;
cursor: pointer;
}
.add-user-btn {
background-color: #343a40;
color: #fff;
border: none;
cursor: pointer;
margin-top: 10px;
}
.task-input {
margin: 10px 0;
}
</style>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js">
</script>
</head>
<body ng-controller="MainController">
<h1 style="color: green;">
GeeksforGeeks
</h1>
<h3>
Approach 2: Using a Function
in the Controller
</h3>
<div ng-repeat="user in users"
class="user-container">
<h2>User {{ $index + 1 }}</h2>
<ul>
<li ng-repeat="task in user.tasks"
class="item">
<span>{{ task.name }}</span>
<button ng-click="showIndex(user, task)"
class="show-index-btn">
Show Index
</button>
<button ng-click="removeTask(user, task)"
class="remove-item-btn">
Remove Task
</button>
</li>
</ul>
<input type="text"
ng-model="newTask"
placeholder="Add a new task"
class="task-input">
<button ng-click="addTask(user, newTask)"
class="add-item-btn">
Add Task
</button>
</div>
<button ng-click="addUser()"
class="add-user-btn">
Add User
</button>
<script>
var app = angular.module('myApp', []);
app.controller('MainController', function ($scope) {
$scope.users = [
{
tasks: [{ name: 'Learn AngularJS' },
{ name: 'Write GeeksforGeeks article' },
{ name: 'Practice JavaScript' }]
},
{
tasks: [{ name: 'Study Algorithms' },
{ name: 'Create Web Apps' }]
}
];
$scope.showIndex = function (user, task) {
var parentIndex =
$scope.users.indexOf(user);
var childIndex =
user.tasks.indexOf(task);
alert("User Index: " + parentIndex +
", Task Index: " + childIndex);
};
$scope.addTask = function (user, newTask) {
if (newTask) {
user.tasks.push({ name: newTask });
$scope.newTask = "";
}
};
$scope.removeTask = function (user, task) {
var index = user.tasks.indexOf(task);
if (index !== -1) {
user.tasks.splice(index, 1);
}
};
$scope.addUser = function () {
$scope.users.push({
tasks: []
});
};
});
</script>
</body>
</html>
Output:
Similar Reads
How to pass the 2 $index values within nested ng-repeat in AngularJS ?
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
5 min read
How to access the Scope from outside JS Function in AngularJS ?
In the AngularJS application, we generally need to access the scope from the outside JS function. This can be done using the global scope object like $rootScope or the AngularJS services. Accessing the scope from the outside of JS functions is to enable the manipulation of data in the scope of the a
4 min read
How to display length of filtered ng-repeat data in AngularJS ?
The task is to Display the length of filtered ng-repeat data. Here we are going to use alias expression to solve this problem. Approach: To display the length of filtered ng-repeat data we use an alias expression. We create an alias for the variable used to filter the ng-repeat data and display the
2 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 use the $index inside a ng-repeat to enable a class and show a DIV in AngularJS ?
In AngularJS applications, we can use the $index variable within an ng-repeat directive to enable a class and show a DIV element based on the index of the current item in the iteration. The $index variable represents the current index of the item being processed in the ng-repeat loop. Similarly, to
6 min read
How to iterate over filtered (ng-repeat filter) collection of objects in AngularJS ?
The task is to iterate over a collection of objects already filtered by ng-repeat filters and after clicking a button, change some property of only those objects which got filtered. Suppose you have a collection of objects that were filtered by a text search within a title property on each object. N
3 min read
How to access the value of a Promise in AngularJS ?
AngularJS is one of the JS frameworks that consists of promises that are used to handle asynchronous tasks. In some scenarios, we need to handle the promise values by accessing them in the application. So, this can be done using the .then() method and also by using the callbacks in AngularJS. In thi
4 min read
How to pass data from Parent to Child component in Angular ?
We can use the @Input directive for passing the data from the Parent to Child component in Angular Using Input Binding: @Input - We can use this directive inside the child component to access the data sent by the parent component. Here app.component is the Parent component and cdetail.component is t
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 filter ng-repeat values according to ng-model using AngularJS ?
In this article, we will see how to filter the value of the ng-repeat directive according to the ng-model directive using AngularJS. The ng-repeat values can be filtered according to the ng-model in AngularJS by using the value of the input field as an expression in a filter. We can set the ng-model
2 min read