Changing color based on AngularJS condition using CSS

My HTML code looks like this:

 <div>
      <i class="glyphicon glyphicon-envelope" 
         style="margin-top: -50px; cursor:pointer; color: #1F45FC" 
         ng-click="createComment(set_id)">
      </i> Route 
      <center>
           <span class="route_no">{{set_id}}</span> 
      </center>
 </div>

 <div>
      <center>Status: {{set.total_one}}/{{set.total_two}}</center>
 </div>

This content is part of an ng-repeat="set in settings"

I am trying to dynamically change the color of my

<i class="glyphicon glyphicon-envelope">
based on a condition set in the JavaScript controller.

I am encountering difficulties in linking each icon with an index so that AngularJS can target specific icons for color changes.

Answer №1

Instead of correcting the classes, you have the option to utilize ng-style to apply a class when the condition is met.

If your condition relies on a boolean property like flag within your set, and if you wish to include a class named red when it's true, you can achieve this by:

<i class="glyphicon glyphicon-envelope"
   ng-click="createComment(set_id)"
   ng-style="{ red: set.flag }">

An alternative approach is to use an expression that generates the class name, where the ternary operator can be very helpful. For instance, if you want the first 3 items to be styled in red and the rest in blue:

<i class="glyphicon glyphicon-envelope"
   ng-click="createComment(set_id)"
   ng-style="$index < 3 ? 'red' : 'blue'">

Answer №2

If you need to determine a color based on certain conditions, you can create a function within your controller to handle this task effectively. Check out the solution provided in this JSFiddle example.

Below is the function that contains the necessary logic for determining the color:

this.pickColor = function (customer) 
{ 
    if (customer.total_one > 400) return 'red';
    if (customer.total_one > 300) return '#FF4700';
    if (customer.total_one > 200) return '#FF9900';
    if (customer.total_one > 100) return 'yellow';
};

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

What is the best way to experiment with angular-ui-tinymce within a tabset using Plunker?

I am currently experimenting with angular-ui-tinymce by incorporating it into a Plunkr. Can anyone assist me in integrating the necessary files for angular-ui-tinymce into the Plunkr so that I can showcase its functionality? Currently, I have this Plunker ...

I added an onClick event to an SVG image, however, I am struggling to get the event to execute a jQuery if/else statement

I've been working on creating an SVG map of the US, and I'm almost finished. The final step involves implementing a simple if-else statement to prompt users for the name of the state when they click on it. My goal is to fill the state green if th ...

The height of the division is either inadequate or excessive when set at 100%

After making progress, I hit a roadblock that has me stumped. The issue I'm facing is with the wrapper height setting. If I set it to auto, it stops at the bottom of the content, leaving the background exposed when the content is shorter than the win ...

ES6 does not support two-way binding functionality

Let's take a look at this snippet of code: export class TestController { constructor() { this.socket = io(); this.movies = {}; this.socket.emit('getAllMovies', ''); this.socket.on('allMovi ...

Encountering a 404 error with Next.js 13 dynamic routing

Whenever I click on an item, it redirects to the dynamic route "http://localhost:3000/products/{id}" but instead of displaying the data, I get an error. Here is my file structure: app components Product.js pages Products [id].js layou ...

Retrieving variables from JavaScript files in TypeScript

Greetings, I am in the process of upgrading an existing Angular application from version 2 to 9. My approach involves first moving it to angular 4 and then continuing with the upgrades. I have successfully updated the necessary packages, but now I'm e ...

Sending unstyled HTML content using JavaMail

Can anyone offer guidance on sending an email using JavaMail with unformatted HTML tags? Here is the code I am currently using: public void sendMail() throws MessagingException, IllegalStateException, IllegalArgumentException { Properties properties ...

POST method is not permitted on Expressjs 405

While the route functions perfectly in POSTMAN's chrome extension, it doesn't seem to work with Angular. Here is my Express js code : var express = require('express'); var router = express.Router(); var app = express(); var bodyParse ...

Detecting a mobile device when using NextJS can be accomplished by using user

With so many topics and questions on Stack Overflow, I am struggling to find the most efficient solution for detecting mobile devices. I have two components - one designed solely for desktops and another for mobile devices. {isMobile? (<SecondComponen ...

Eliminating the bottom border of all buttons, except for the last three buttons in the list, solely using pure JavaScript, unless alternative methods are available

I have 3 sets of buttons, with each set containing 9 buttons stacked in 3 columns inside an ordered list (ol) within list items (li). I have removed the bottom border of the buttons to avoid double borders since they are stacked on top of each other withou ...

Retrieving the value from a concealed checkbox

I have been searching everywhere, but I can't seem to find a solution to this particular issue. There is a hidden checkbox in my field that serves as an identifier for the type of item added dynamically. Here's how I've set it up: <inpu ...

Storing a Promise in a Variable in React

As a newcomer to JavaScript/React, I am finding it challenging to grasp the concept of using Promise and async. To illustrate, consider the API call getSimById in a JS file that returns a Promise: export function getSimById(simId) { return fetch(simsUrl ...

How come I'm not receiving an error message when I enter an incorrect email or password?

Whenever I try to log in with the wrong password and email, no error message is displayed. Instead, it simply logs me in and takes me to the main page. Can someone please assist me in implementing an error message display for incorrect login details? imp ...

Having trouble with my JavaScript code in Visual Studio because of a bundler issue. It's throwing an Uncaught ReferenceError for trying to access a variable before initialization

My AJAX request looks like this: $.ajax({ method: 'GET', url: '/api/some-data', headers: { 'Content-Type': 'application/json' }, success: function(data) { if (data != null) { var userDat ...

Margin discrepancies when using em units

Currently, I am utilizing an em-based margin for items within a menu that are homogeneous in terms of markup, class, and id. It appears that the margins for each of these items should be rendered the same. However, some are displaying as 1px while others a ...

Error in Fullcalendar Angular/Node.JS http request: Circular structure detected during JSON conversion (at Object.stringify)

Encountering a "TypeError: Converting circular structure to JSON at Object.stringify (native)" error while attempting to update by http call on fullcalendar drop event. Below is the client side code snippet: drop: function() { $scope.schedule. ...

The function req.send('null') does not exist in the Node.js MySQL library

I am struggling with inserting a form into a MySql database. The values are stored in the database from the form, but the table displayed on the page does not refresh. I can only see the entries when I restart the server and revisit the page. Furthermore, ...

Is it possible to make an image gradually appear and disappear?

Is there a way to create a continuous fade in and out effect for an image, transitioning between 40% and 100% opacity? I attempted using a CSS3 opacity property, but it only allows for 0% and 100%, causing the fade effect to be ineffective. Does anyone h ...

Is there a way to update an angular.js service object without using extend or copy?

I am working with 2 services and need to update a variable in the first service from the second service. Within a controller, I am assigning a scope variable to the getter of the first service. The issue I am facing is that the view connected to the cont ...

Organizing items in rows with alternating quantities using CSS within a fluid design

Encountering a peculiar issue while attempting to organize items spread across multiple rows, with each row having either 5 or 4 items (alternating between 5 and 4 items per row). However, when the screen width reaches 480px, the layout automatically switc ...