Open In App

How to use the $index inside a ng-repeat to enable a class and show a DIV in AngularJS ?

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

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 show or hide a DIV element, you can use the ng-show or ng-hide directives, again utilizing the $index to control the visibility of the element. In this article, we will see 2 different approaches to using the $index inside a ng-repeat to enable a class and show a DIV in AngularJS.

Steps to Configure the AngularJS Applications

The below steps will be followed to configure the AngularJS Applications:

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 index-repeat
cd index-repeat

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 examples.

Implementing $index inside a ng-repeat using ng-class and ng-click Directive

In this approach, we’re using the “ng-class” and “ng-click” directives to enable user interactivity. The list items in the “items” array are displayed, and when a user clicks on an item, it becomes highlighted using the “active” class, and the corresponding item details are shown. The “selectedIndex” variable is used to keep track of the selected item’s index. Users can also edit or delete items, and there’s an option to add new items to the list. This approach offers a dynamic and engaging user experience by toggling the display of item details and enabling various actions such as editing and deleting items.

Example: Below is an example that demonstrates the use of the $index inside a ng-repeat to enable a class and show a DIV in AngularJS using ng-class and ng-click Directive.

HTML




<!DOCTYPE html>
<html ng-app="myApp">
  
<head>
    <script src=
    </script>
    <style>
        .active {
            background-color: #ffcc00;
            color: #333;
        }
          
        .hidden {
            display: none;
        }
          
        .fade-in {
            animation: fadeIn 0.5s;
        }
          
        .item-details {
            border: 1px solid #ccc;
            padding: 10px;
            margin-top: 10px;
            background-color: #f7f7f7;
        }
          
        .edit-button,
        .delete-button {
            background-color: #007BFF;
            color: white;
            border: none;
            padding: 5px 10px;
            cursor: pointer;
            margin-top: 10px;
        }
          
        h1 {
            color: green;
        }
          
        @keyframes fadeIn {
            from {
                opacity: 0;
            }
          
            to {
                opacity: 1;
            }
        }
    </style>
</head>
  
<body ng-controller="MyController">
    <div class="container">
        <h1>GeeksforGeeks</h1>
        <h3>
            Approach 1: Using ng-class and ng-click
        </h3>
        <ul>
            <li ng-repeat="item in items" 
                ng-class="{ 'active': $index === selectedIndex }">
                <a ng-click="toggleDiv($index)">
                    {{ item.name }}
                </a>
            </li>
        </ul>
        <div ng-repeat="item in items" 
             ng-show="$index === selectedIndex"
             ng-class=
             "{ 'hidden': selectedIndex === -1, 
                'fade-in': selectedIndex !== -1 }">
            <p>{{ item.description }}</p>
            <button class="edit-button" 
                    ng-click="editItem(item)">
                    Edit
            </button>
            <button class="delete-button" 
                    ng-click="deleteItem($index)">
                    Delete
            </button>
        </div>
        <div>
            <h2>Add New Item</h2>
            <input type="text" 
                   ng-model="newItemName"
                   placeholder="Item Name" />
            <input type="text" 
                   ng-model="newItemDescription"
                   placeholder="Item Description" />
            <button ng-click="addItem()">
                Add Item
            </button>
        </div>
    </div>
    <script>
        var app = angular.module("myApp", []);
        app.controller("MyController", function ($scope) {
            $scope.items = [
                { name: "GeeksforGeeks Article 1",
                  description: "Learn about AngularJS" },
                { name: "GeeksforGeeks Article 2",
                  description: "Explore JavaScript" },
                { name: "GeeksforGeeks Article 3", 
                  description: "Master Web Development" },
            ];
            $scope.selectedIndex = -1;
            $scope.newItemName = "";
            $scope.newItemDescription = "";
            $scope.toggleDiv = function (index) {
                if ($scope.selectedIndex === index) {
                    $scope.selectedIndex = -1;
                } else {
                    $scope.selectedIndex = index;
                }
            };
            $scope.editItem = function (item) {
                alert("Editing item: " + item.name);
            };
            $scope.deleteItem = function (index) {
                if (confirm(
                    "Are you sure you want to delete this item?")) {
                    $scope.items.splice(index, 1);
                    $scope.selectedIndex = -1;
                }
            };
            $scope.addItem = function () {
                if ($scope.newItemName && $scope.newItemDescription) {
                    $scope.items.push({
                        name: $scope.newItemName,
                        description: $scope.newItemDescription,
                    });
                    $scope.newItemName = "";
                    $scope.newItemDescription = "";
                }
            };
        });
    </script>
</body>
  
</html>


Output:

Ex1

Implementing $index inside a ng-repeat using ng-click and ng-if Directive

In this approach, we have used “ng-clickandng-if,” and we’ve created an interactive shopping cart. Each item in the cart is listed, and when a user clicks on an item, it becomes highlighted with the “highlighted” class, and its details are revealed. Users can adjust the quantity, add items to the cart, and see the total cost in Indian Rupees (₹). The approach focuses on toggling the display of item details using “ng-click” and “ng-if” based on the index within an “ng-repeat” loop.

Example: Below is an example that demonstrates the use of the $index inside a ng-repeat to enable a class and show a DIV in AngularJS using ng-click and ng-if Directive.

HTML




<!DOCTYPE html>
<html ng-app="myApp">
  
<head>
    <script src=
      </script>
    <style>
        .highlighted {
            background-color: yellow;
        }
  
        .shopping-cart {
            border: 1px solid #ccc;
            padding: 10px;
            margin: 10px;
            background-color: #f5f5f5;
        }
  
        h1 {
            color: green;
        }
  
        .currency {
            font-size: 1.2em;
        }
    </style>
</head>
  
<body ng-controller="ShoppingController">
    <h1>GeeksforGeeks</h1>
    <h3>Approach 2: Using ng-click and ng-if</h3>
    <div class="shopping-cart">
        <h2>Shopping Cart</h2>
        <ul>
            <li ng-repeat="item in cart" 
                ng-class=
                "{ 'highlighted': $index === selectedIndex }">
                {{ item.name }} - Price: ₹{{ item.price }}
                <button ng-click="toggleDetails($index)">
                      Toggle Details
                  </button>
                <div ng-if="$index === selectedIndex">
                    Details:
                    <p>{{ item.description }}</p>
                    <label>Quantity:</label>
                    <input type="number" 
                           ng-model="item.quantity" 
                           min="1">
                    <button ng-click="addToCart(item)">
                          Add to Cart
                      </button>
                    <p>
                          Total: ₹{{ item.quantity * item.price }}
                      </p>
                    <button ng-click="removeFromCart(item)">
                          Remove from Cart
                      </button>
                </div>
            </li>
        </ul>
        <h3>Your Shopping Cart</h3>
        <ul>
            <li ng-repeat="item in cart"
                ng-show="item.inCart">
                {{ item.name }} - Quantity: {{ item.quantity }} -
                  Total: ₹{{ item.quantity * item.price }}
                <button ng-click="removeFromCart(item)">
                      Remove
                  </button>
            </li>
        </ul>
        <p class="currency">
              Total Cart Price: ₹{{ getTotalCartPrice() }}
          </p>
        <button ng-click="clearCart()">
              Clear Cart
          </button>
    </div>
</body>
<script>
    var app = angular.module('myApp', []);
    app.controller('ShoppingController', function ($scope) {
        $scope.cart = [
            { name: 'Item 1', 
              price: 10, 
              description: 'A nice item for your shopping cart.', 
              quantity: 0, 
              inCart: false },
            { name: 'Item 2', 
              price: 15, 
              description: 'Another great item to consider.', 
              quantity: 0,
              inCart: false },
            { name: 'Item 3', 
              price: 20, 
              description: 'The best item you can have.',
              quantity: 0,
              inCart: false }
        ];
        $scope.selectedIndex = -1;
        $scope.toggleDetails = function (index) {
            if ($scope.selectedIndex === index) {
                $scope.selectedIndex = -1;
            } else {
                $scope.selectedIndex = index;
            }
        };
        $scope.addToCart = function (item) {
            item.inCart = true;
        };
        $scope.removeFromCart = function (item) {
            item.inCart = false;
            item.quantity = 0;
        };
        $scope.getTotalCartPrice = function () {
            var total = 0;
            for (var i = 0; i < $scope.cart.length; i++) {
                if ($scope.cart[i].inCart) {
                    total += 
                      $scope.cart[i].quantity * $scope.cart[i].price;
                }
            }
            return total;
        };
        $scope.clearCart = function () {
            for (var i = 0; i < $scope.cart.length; i++) {
                $scope.cart[i].inCart = false;
                $scope.cart[i].quantity = 0;
            }
        };
    });
</script>
  
</html>


Output:

Ex2



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads