How to use the $index inside a ng-repeat to enable a class and show a DIV in AngularJS ?
Last Updated :
26 Jul, 2024
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.
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=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js">
</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:
Implementing $index inside a ng-repeat using ng-click and ng-if Directive
In this approach, we have used "ng-click" and "ng-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=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js">
</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:
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 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 usi
6 min read
How to select an element by its class name in AngularJS?
Given an HTML document and the task is to select an element by its className using AngularJS. The elements can be selected with the help of a class name using the document.querySelector() method that is used to return the first element that matches a specified CSS selector(s) in the document. Approa
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 show/hide data when the particular condition is true in AngularJS ?
In AngularJS, in order to hide or show data or content, we can use the *ngIf structural directive. By using this, we can evaluate conditions and then *ngIf based on the condition displays the content. For example, if the condition for *ngIf is true then the content will be displayed and if the condi
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
How to Sort an Array based on User Input in AngularJS ?
AngularJS is a JavaScript-based framework. It can be used by adding it to an HTML page using a tag. AngularJS helps in extending the HTML attributes with the help of directives and binding of data to the HTML with expressions. In this article, we will see how to sort an array based on user input in
3 min read
What is the equivalent of ngShow and ngHide in Angular 2+?
ngShow and ngHide are two ng directives in AngularJS used to show and hide the elements respectively. ngShow is used to show a div tab by linking it to a Boolean variable in the script. If the value of the variable is true then the item is displayed, else the item remains hidden and the vice versa h
3 min read
How to render an Object in a Sorted order based upon Key in Angular ?
An Object is a collection of properties, and a property is an association between a name (or key) and a value. A Property's value can be a function, in which case the property is known as a method. To achieve this, we can display the object's properties in a particular order, where the order is dete
3 min read