Utilizing AngularJS to dynamically apply CSS classes based on the $index value

Is there a way to style my div based on the ng-repeat index, applying different styles for odd and even rows? The row with an even index should have all classes specified for the odd one plus additional classes.

Controller:

 var odd = { 'class1': true, 'class2': true, 'class3': false, 'class4': false };
var even = { 'class1': true, 'class2': true, 'class3': true, 'class4': true };

$scope.applyColumnClasses = function(index) {
    if (index % 2 === 0)
        return even;
    else
        return odd;
}

View:

<div ng-repeat="a in articles" ng-class="applyColumnClasses($index)">

I have more than five classes that need to be added to the even row. Is there a more elegant solution? Maybe setting a string variable as "class1, class2" for odd rows, then appending additional classes for even rows before returning it.

I aim to write cleaner code and may benefit from declaring a single object instead of two as I currently have.

Any suggestions or thoughts?

Answer №1

Here are two methods :

class="commonClass" ng-class="{'evenClass':$even,'oddClass':$odd}"

or

class="commonClass"  ng-class-even="'evenClass'" ng-class-odd="'oddClass'"

Answer №2

To easily add common classes without the need for binding, simply apply them directly and keep the rest intact:

<div  ng-repeat="a in articles" class="class1 class2" ng-class="applyColumnClasses($index)" >

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

TestingCompilerFactory is not available as a provider

Currently troubleshooting my test file to identify the issue that is hindering a successful test run: import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { Component, Directive, Input, OnInit } from '@angula ...

Issue arises when component is mistakenly displayed in the header upon deployment on Vercel platform

When deploying my NextJS app to Vercel, I encounter an issue where state-based modals that should be hidden are displaying. Additionally, the modals are rendering in the header instead of center-screen as expected. Surprisingly, these problems do not occur ...

What could be causing my webGL page to fail loading the second time following a refresh?

My friend and I are working on a JavaScript page together. Initially, the page loads smoothly when opened in a tab, although it may be a bit slow. However, upon refreshing the tab, the WebGl canvas appears completely blank while the HTML elements are stil ...

apply a course to the designated element

Alright, I have this piece of code that deals with session and page requests. // Let's start our session session_start(); // Now let's check if there is a page request if (isset($_GET['page'])) { // If there is a requested page, we ...

Ways to launch the React Material date picker while hiding the date input field

I am working with the react material (MUI-X) date picker and my specific requirement is to have the date picker open on button click without displaying the date text field. I simply want to show the calendar and allow users to select a date. I have explore ...

Is it feasible to send props to { children } within a React functional component?

Workaround presented below. I am attempting to send props down to a child component using {children}. The Parent component: const ParentComp = ({ children, propsToSendToChild }) => ( <div>Dynamic component content: {children} &l ...

Drawing an image on an Ionic 4 canvas using the drawImage method, following a change

I've been working on an app that displays an image on a canvas, with the image source coming from the parent page. Everything seems to be functioning correctly, but when I try changing the imageSrc via a button click, the canvas ends up blank. Oddly ...

Unable to retrieve input field in protractor testing

Struggling with accessing an input field in AngularJS/Protractor for testing purposes. Despite the app setting the input fields to their initial values when running on the browser, I am unable to interact with them or modify their contents during testing. ...

jQuery Datatables provide a powerful and customizable way to display

I've been working on a project that requires me to incorporate Grid functionality into the displayed data. To achieve this, I'm utilizing the Datatable plugin from jquery. The implementation is smooth and flawless. However, a concern arises wh ...

When attempting to load the table from JSON, the error message "Cannot read property 'name' of null" occurs in the fooplugins/Footable plugin

I am facing an issue while trying to integrate the "FooTable" plugin with ajax calls. Everything works perfectly fine when I directly input the JSON data or load it from a JSON file using $.get('....json'). However, when attempting to fetch the t ...

HTML - Automated Navigation to Anchor Links

My website features a search box and various options. While the mobile version displays these prominently on the start page, once a user performs a search, the result page also includes the search box and options at the top. To streamline the user experie ...

Entity Framework and the GET request error: Connection Reset

Currently, I am working on developing a straightforward notes application using Entity Framework in ASP.Net Core for the backend and AngularJS for the frontend. The main objective is to have the app load a pre-existing list of notes from my MySQL database ...

What is the method for ensuring the banner image is visible behind the transparent navigation bar?

I recently used Bootstrap 4 to write the code below. In the image provided, I have outlined what my goal is with this code. Thank you! https://i.sstatic.net/oB6b6.jpg <style> div.jumbotron { background: #458392 url("img/ban ...

Launching the Node.js application on Heroku resulted in encountering an issue: "Application error - There was a problem within the application

When I access the browser using http://localhost:8080/, I can see the message Hello World with Express. I am currently trying to deploy this application on Heroku. I have followed the tutorial provided by Heroku. 1) Create a new app 2) Choose an App name ...

Simulate internationalization for vue using jest

Currently, I am working on setting up jest unit tests for a Vue project within a complex custom monorepo. I am facing an issue with i18n, which I use for translation management in my application. The problem arises with the following code snippet for init ...

Tips for defining a distinct series of key-value pairs in typescript

Having experience with a different language where this was simple, I am finding it challenging to articulate a sequence of pairs: Each pair is made up of two basic elements (such as strings or numbers) Each element may appear multiple times within the lis ...

Guide on interpreting unordered lists and returning the outcome to Java

The xhtml-file provided below showcases a structure for content creation: <ui:composition xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" temp ...

What is the best way to trim a string property of an object within an array?

I am seeking a solution to access the "description" property of objects within an array and utilize a string cutting method, such as slice, in order to return an array of modified objects. I have attempted using for loops but have been unsuccessful. Here ...

Adjust the width of a jQuery Mobile control group

Having trouble resizing a control group using jQuery Mobile 1.3.0 Seeking the correct approach, currently attempting to resize the .ui-btn class with the following code: #test_1 .ui-btn { width: 200%; } The buttons are not resizing as expected; when ...

Tips for incorporating Action Links into your CSS workflow

<li class="rtsLI" id="Summary"><a href="javascript:void(0);" onclick="javascript:rtsXXX.OnClientTabSelected(this‌​, 0);" class="rtsLink"><span class="rtsTxt">Test</span></a></li> I have made a change by replacing th ...