How to dynamically add a class in ng-repeat using AngularJS

Currently, I am utilizing AngularJS ng-repeat to loop through some data. However, I am trying to create a grid layout and want to apply a 'grid--last' class to the 4th item in the grid. Is there a way to achieve this?

This is what my HTML looks like:

<div ng-repeat="service in services" class="grid__4">
                <div class="services__box">
                    <img src="img/services/{{service.thumb}}.jpg" alt="" class="services__box__img">
                    <h1 class="services__box--alpha alpha">{{service.title}}</h1>
                    <p>
                        {{service.text}}
                    </p>
                    <a href="{{service.url}}.php" class="services__box--btn btn btn--blue">{{service.button}}</a>
                </div>
            </div>

I am looking to determine the index of the array and utilize ng-class for this task. Any suggestions on how to get this done would be greatly appreciated. Thank you!

ng-class="{}"

Answer №1

When using Angular's repeat scope, you have access to the special $index property. This allows you to apply conditional classes based on the index position of each item in the loop. For example, you can use

data-ng-class="{'grid--last': $index == 3}"
to target the fourth item in the loop (since indexes start at 0).

Answer №2

Applying this effect can be achieved using CSS, but it's important to note potential compatibility issues with older versions of Internet Explorer (such a surprise!)

Check out the code snippet here

Here is the relevant code snippet:

<style>
      li.item {
        background-color:blue;
      }

      li.item:last-child {
       background-color: red;
      }
    </style>
  </head>

  <body ng-controller="testCtl">
    <ul>
      <li class="item" ng-repeat="val in [1, 2, 3, 4]">{{val}}</li>
    </ul>
  </body>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it considered a best practice to use collection.find() to retrieve all items on a master node in Mongo?

Every night at midnight, a background process retrieves all users from MongoDB and performs various checks and processes on their accounts. I have some questions regarding this process: Is it efficient in terms of performance to use the following query t ...

When activating a bootstrap class button, I must ensure the reply-box remains hidden

let replyButton = document.getElementById('reply-button'); let cardBody = document.getElementById('card-body'); let responseBox = document.getElementById('reply-box'); let cancelButton = document.getElementById('btn btn-d ...

Having trouble with Javascript not detecting when it's empty?

Recently, I have been attempting to modify the color of a submit button when a form is empty. As a beginner in this area, I am somewhat puzzled as to what mistake I might be making. I will share the current code with you in hopes of receiving some guidance ...

Unable to retrieve req.body data, despite having body-parser enabled

I've been working on setting up my login functionality, but I'm running into an issue with accessing the req.body object. Initially, the post route wasn't triggering at all (no console.log output in terminal) and the request would eventuall ...

The content of XMLHttpRequest is accessible via the property response

Typically, when we want to retrieve data using AJAX, we would use code like this: var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function(){ if(xhr.readyState == 4 && xhr.status == 200){ elem.innerHTML = xhr.responseText; ...

The onChange function does not seem to be functioning properly within the Reactstrap customized input switch

Here is some code: import { CustomInput } from 'reactstrap' ... const changeMediaStatus = (e) => { console.log(e) } ... <CustomInput type="switch" className="ml-auto mr-1" onChange={(e) =>changeMediaStatus ...

Having trouble finding the element within the form tag even after attempting to use .switchTo().defaultContent()

My HTML is structured like this: <section> <div> <form> <div>Username field</div> <div>Password field</div> <div> <div>.. <div>.. <iframe& ...

Discovering image file extensions in JavaScript using regular expressions

Can anyone provide me with a javascript regular expression to validate image file extensions? ...

Verification of phone numbers in HTML

Currently, I am facing a dilemma while working on an HTML website. The client's requirement is to allow only numerical phone numbers without any alphabetic characters. The condition set is that the phone number field should accept and submit a phone ...

The utilization of React context is unsuccessful

Utilizing react context to pass the username across different components has been a challenge for me. I have structured my project into 3 main pages: - app.js - signIn (where the username is updated) - page1 (where I intend to display the updated username) ...

Using React.js with a PHP backend to create an API ecosystem for

Creating an admin panel for a website with CRUD operations has been quite the journey. I began by setting up API endpoints and hosting them on a subdomain. Fetching data from these endpoints was successful for displaying all contacts (GET), individual cont ...

Preview and enlarge images similar to the way Firefox allows you to do

When you view an image in Firefox, it is displayed with the following characteristics: Centered within the browser window. Has a height/width that fits within the browser dimensions. Does not resize larger than its maximum size. Remains the same size if ...

Modifying the Readonly Attribute of an ASP.NET Web Application with the Power of JQuery

Check out this snippet of HTML code <td style="width: 4pt;"> </td> <td> <span style="display: inline-block; color: Black; font-family: Arial; font-size: 9pt; font-weight: normal; width: 100pt; vertical-align: top;"> ...

Different techniques for using percentages in CSS transformations to create dynamic animations for DOM element translations

I have 14 objects positioned across the dom that I need to animate using the translate property. Currently, I am using transform: translate(x%, y%) for each object, requiring me to calculate the translation amount and apply a CSS style individually. This m ...

Is using Javascript objects a better alternative to Redux?

I'm in the process of creating my initial application with React and have opted to integrate Redux into it. Since incorporating Redux, it appears that setting a component state to a basic global JavaScript object would be a simpler approach. I unders ...

Eliminate HTML tags when CKEDITOR is switched

I recently switched from a normal textarea to CKEDITOR, with a toggle button that allows users to switch between the two. However, I encountered an issue where HTML tags are not removed after destroying CKEDITOR if there was existing content in it when swi ...

Changing quotations to parentheses using Javascript Regular Expressions

Is there a way to utilize a regex in Javascript to replace the string sequence "*" with (*)? I'm looking to replace items between quotes with items enclosed in opening and closing parenthesis. For instance, transforming "apple" to (apple). Do you ha ...

Incorporating React.js into HTML DOM Elements

As a beginner in react js, I'm facing an issue regarding DOM elements. Within my component, there is a table. When hovering over a cell, I want to highlight both the corresponding row and cell. Additionally, I need to obtain the coordinates of the hov ...

Netlify encountered an error with mixed content, indicating that the page was successfully loaded over HTTPS, but it attempted to request an insecure HTTP

hey everyone, Recently, I deployed my vue-cli website project on Netlify. However, upon opening the website, I encountered the following error message: Mixed Content: The page at 'https://xxxx.netlify.app/' was loaded over HTTPS, but requested a ...

TopoJSON conversion leading to surprising shapes and figures not found in original JSON

I am trying to showcase the topoJSON on a leaflet map using d3. To achieve this, I am following an example on GitHub available at this link. Here is the code I have extracted from the GitHub example: <!DOCTYPE html> <html lang="en"> <head ...