Using different CSS classes interchangeably in AngularJS

Imagine you have a list with an unknown number of items, ranging from one to potentially dozens. You want to display five CSS classes in a regular alternating pattern. What would be the most effective approach to achieve this?

Here is some sample HTML code:

<div ng-repeat="item in items | orderBy: 'Title'">
    <div class="clearfix" ng-if="$index % 3 == 0"></div>
    <div class="col-sm-4">
        <div class="tile" ng-class="{ 'purple': expression1, 'red': expression2, 'green': expression3, 'blue': expression4, 'orange': expression5 }">
            <h3 class="title">{{item.Title}}</h3>
            <div>{{item.Description}}</div>
        </div>
    </div>
</div>

Here are the corresponding CSS styles:

.tile.purple {
    background: #5133ab;
}
.tile.red {
    background: #ac193d;
}
.tile.green {
    background: #00a600;
}
.tile.blue {
    background: #2672ec;
}
.tile.orange {
    background: #dc572e;
}

Is there a preferred method for consistently alternating these classes as shown in the example provided?

Answer №1

angular.module('myApp', [])
.controller('MyCtrl', function($scope) {
  $scope.items = [1,2,3,4,5,6,7,8,9,10];
  // create an array of color classes
  $scope.colors = ['purple', 'red', 'green', 'blue', 'orange'];
})
;
<div ng-app="myApp" ng-controller="MyCtrl">
  <div ng-repeat="item in items">
    <!-- using modulus operator to determine the appropriate color class for each item -->
    <div class="tile" ng-class="colors[$index % colors.length]">{{item}}</div>
  </div>
</div>

Check out the live demo by clicking here.

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

Sending variables to other parts of the application within stateless functional components

My main component is Productos and I also have a child component called EditarProductos. My goal is to pass the producto.id value from Productos to EditarProductos. Here is my Productos component code: import {Button, TableHead, TableRow, TableCell, Tabl ...

Error encountered: `npm ERR! code E503`

While attempting to execute npm install on my project, which was cloned from my GitHub repository, I encountered the following error: npm ERR! code E503 npm ERR! 503 Maximum threads for service reached: fs-extra@https://registry.npmjs.org/fs-extra/-/fs-ex ...

Tips for integrating Apache Solr with Cassandra without using DataStax Enterprise (DSE)

Embarking on a new project, I find myself utilizing Cassandra as the chosen DBMS, with Apache Solr serving as the search engine and Node.js powering the server scripting language. While I am well-versed in Node.js, Cassandra and Solr are unfamiliar territ ...

Retrieving ID of an element to be animated with jQuery

I have a sprite image that changes background position when hovered over, and while it's currently working, I'm looking for a more efficient way to achieve this. I need to apply this effect to several images and am exploring ways to avoid duplica ...

Finding the element '54' using protractor, without relying on xpath

Having trouble finding the number 54 (or the entire internal div) in this HTML snippet. I prefer not to use xpath since my page structure changes based on search results. Is there a way to locate it using CSS, maybe? PS: I'm testing an Angular applic ...

Encountering a Selection Issue with IE8

I am encountering an issue with my script that involves a form with two select elements for region and state, allowing users to filter states based on the selected region. Everything works smoothly except for one problem - when testing in IE8, I receive th ...

Issues connecting a model to a custom directive in Angular

I have been working on getting two multiselect widgets to sync with each other, but have only succeeded in achieving one-way synchronization. One widget is located on the main page, while the other is in an angular ui-bootstrap modal. Both multiselect wid ...

Executing multiple requests simultaneously with varying identifiers following a waiting period

I am looking to send a GET request using the user_id key retrieved from the userData object. This is how the request should be structured: Let's assume we have userData defined as follows: var userData = [ { id: 1, user_id: ...

Establishing updated file path for resources in JavaScript based on environment

I'm currently facing an issue with my external Javascript file that uses the getScript() function to execute another JS file. Both files are located on static.mydomain.com, as I am trying to set up a Content Delivery Network (CDN) for the first time. ...

Combining Extjs combo with autocomplete functionality for a search box, enhancing synchronization capabilities

When using autocomplete search, I've encountered an issue. If I type something and then make a mistake by deleting the last character, two requests are sent out. Sometimes, the results of the second request come back first, populating the store with t ...

bitcoinjs-lib for generating raw transactions in Node.js

var bitcoin = require('bitcoinjs-lib'); var rp = require('request-promise'); var data = Buffer.from('Hello World', 'utf8'); var testnet = bitcoin.networks.testnet; var privateKey = 'p2pkh'; var SourceAddre ...

Embed script tags into static HTML files served by a Node.js server

Looking to set up a Node server where users can request multiple pages from a static folder, and have the server inject a custom tag before serving them. Has anyone had success doing this? I've tried with http-proxy without success - not sure if a pro ...

Sort div elements based on checkbox filters

I have a set of checkboxes that I want to use for filtering purposes. <div class="filter"> <div class="checkbox"> <label><input type="checkbox" rel="canada"/>Canada</label> </div> <div class="chec ...

Utilizing CSS to Properly Position HTML Elements

Check out my code on jsFiddle I'm facing some challenges in positioning HTML elements using CSS. While I grasp the fundamental concepts of block and inline elements, implementing them in real coding scenarios can be confusing. I've shared my HTM ...

Issue with updating nested child object reference in Redux state input value

I have a function in redux that updates an object with a specified path and value. The inputs on my page are based on the values in the object stored in state. Whenever the listingObj is modified in redux, I want the DOM to automatically refresh. This i ...

Implement an onClick event to the newly created th element using document.createElement()

Through the use of document.createElement("th"), I am dynamically inserting columns into a table. var newTH = document.createElement('th'); Is there a way to add an onClick attribute to this element so that users can delete a column by clicking ...

Utilizing AngularJS: Dynamically employ custom directives for enhanced reusability

I am currently developing my debut single page Angular.js application and finding myself in a bit of a rut when it comes to programmatically compiling/evaluating a custom directive to insert it into the DOM from within a controller. The custom directive I ...

Adding padding-top to the h1 element within a vertically aligned div

I have a div with a set height and the content inside adjusts vertically according to the height. To align it vertically, I added the property display-table; to the parent div and display: table-cell; vertical-align: middle; to the child div. The alignment ...

I am encountering issues where none of the NPM commands are functioning properly even after updating the

For a few months, I have been using npm without any issues. However, once I installed python/django and created a virtual environment, npm stopped working altogether. An error message similar to the following is displayed: sudo npm install -g react-nativ ...

What is the best way to position a title and subheading alongside an image?

I am currently working on developing a blog using php and html to enhance my coding skills. On my website, I have a special category where I display posts, the number of which can vary. Each post is composed of a title, a subheading, and a placeholder div ...