Open In App

How to access index of the parent ng-repeat from child ng-repeat in AngularJS ?

Last Updated : 19 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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.

Steps to Configure the Angular Application

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=
      </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:

Ex1

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=
      </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:

Ex2



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads