Open In App

How to pass the 2 $index values within nested ng-repeat in AngularJS ?

Last Updated : 28 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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

e1

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

e2



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads