Maximizing the Use of Multiple Conditions for Styling in AngularJS

I have a table where I need to set different colors based on the values in one of the columns. I've successfully managed to set two colors using NgClass, but I'm unsure how to set up three different conditions.

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<tr ng-class="{{project.total >= 0}} ? 'danger':'success'">

  <td>
    {{project.total}}
  </td>

</tr>

I want to set up three conditions based on the 'total' column values: if total is less than 35, the color should be red; if it's between 35 and 70, it should be yellow; and if it's above 70, it should be green. How can I achieve this using Angular? Keep in mind, I am very new to Angular.

Answer №1

If you want to assign a value of an object to the ng-class attribute, it is possible.

As stated in the official documentation :

When the expression evaluates to an object, each key-value pair will use the corresponding key as a class name if the value is truthy.

Your object structure should look like this :

{
    'red': project.total < 35,
    'yellow': project.total >= 35 && project.total < 70,
    'green': project.total >= 70
}

Therefore, your html code will be as follows :

<tr ng-class="{ 'red': project.total < 35, 'yellow': project.total >= 35 && project.total < 70, 'green': project.total >= 70 }">

Edit: You can check out the demo fiddle

However, due to angular's digest mechanism, it is recommended to use simple conditions in your templates. The class calculation can be moved to the controller, resulting in a simpler template code like this :

<tr ng-class="{{project.class}}">

Answer №2

<tr ng-class="{'red': project.total <35  , 'yellow':project.total >= 35 && project.total<70,'green': project.total >= 70 } ">

Answer №3

It is recommended to handle complex tasks like this in a controller rather than directly in the HTML. However, if you really want to, you can achieve it like this:

<tr ng-class="project.total < 35 ? 'danger': (project.total < 71 ? 'partial' : 'success')">

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

Adding Jade template variable to an inline function

Trying to implement the JSCharts library. block content | <div id="chartcontainer">This is just a replacement in case Javascript is not available or used for SEO purposes</div> script. var myData=new Array() var myData = new Array([10 ...

Vue email validation is failing to return a valid email address

I'm relatively new to Vue and have implemented email validation using the reg expression in my Vue script data for this project. By utilizing console.log(this.reg.test(this.email)) and observing the output while users input their email, the validation ...

Limit Javascript Regex to accept only one specific possibility and exclude all others

Here are the specific validations I need for my URL: cars : valid cars/ : valid (Accepting any number of '/' after "cars") cars- : invalid cars* : invalid carsp : invalid (Rejecting any character after "cars" except '/') **cars/ne ...

"Automating the process of toggling the edit mode of a contenteditable element – how is

Is there a specific event I can use to programmatically start or stop editing a contenteditable element, similar to when the user focuses or blurs it? I have tried using .focus(), .click(), and even setting the selection to its content, but none of them se ...

Empty Angular-chart.js Container

How can I resolve the issue of getting a blank div and no output while trying to display a chart where the options, labels, and other data are initialized in the TypeScript controller and then used on the HTML page? I added the angular-chart.js library us ...

"Declare the Status, Refresh the Page, and Specify the Web

After refreshing the page, I am facing an issue where the text corresponding to the current URL is not being displayed. My application consists of a Main component that renders a MiniDrawer component containing a NavLink, followed by routing with the Route ...

Is there a way to dynamically alter the theme based on stored data within the store

Is it possible to dynamically change the colors of MuiThemeProvider using data from a Redux store? The issue I'm facing is that this data is asynchronously loaded after the render in App.js, making the color prop unreachable by the theme provider. How ...

What are the practical applications and distinctions between single-page and multipage apps in AngularJS?

I've been exploring the differences between single page apps and multi page apps, and I believe I have a good grasp on their distinctions. Unlike multi page apps, a single page app begins by loading a single HTML page and does not fully refresh or ove ...

Deciphering Encrypted JSON Data

In need of help with our app that generates complex JSON objects where properties and values are in hexadecimal format. How can we convert them back to strings? Example Object: { "636f756e747279": { "6e616d65": "43616e616461", "6 ...

Guide on invoking a node.js function from an express-rendered ejs page

My express server currently has a button that triggers a POST request to activate a function in my node.js server. Instead of using a traditional POST request, I am interested in implementing something like AJAX so that the page doesn't reload. Is th ...

When an image is loaded, use Jquery to automatically open a new tab, instead of

I need to implement a function where, on loading an image on a page, a new tab opens and starts downloading a file from a specific URL while keeping the original page open. This task is part of a WordPress site with a jQuery section in the backend. I' ...

What is the best way to incorporate an array of elements into Firebase?

How can I store data from an array to Firebase in a simple manner? Let's say I have an array of elements. function Something() { var elements=new Array() elements[0]=10; elements[1]=20; elements[2]=30; database = firebase.databas ...

Not waiting for all HTTP calls to finish before returning the service

I have a situation where my controller is calling a service that makes several HTTP calls and returns a dataset to the controller. The issue I'm encountering is that the service sometimes returns data (usually empty) before all the HTTP calls are fini ...

Utilizing $resource within a promise sequence to correct the deferred anti-pattern

One challenge I encountered was that when making multiple nearly simultaneous calls to a service method that retrieves a list of project types using $resource, each call generated a new request instead of utilizing the same response/promise/data. After doi ...

Steps to display a div on top of a background image

Here is a visual representation of my design for better understanding: I am currently working on developing the central content that overlays the image. However, when I insert divs with background colors into my HTML to test their placement, I do not see ...

Error with AngularJS Routing

During the development of my asp.net mvc project with angularjs routing, I encountered some routing errors when reloading pages. In my application, .when('/home', { templateUrl: '/Selection_Routing/Selection_Product/Home.html&ap ...

Is it necessary for the key in JSON syntax to be enclosed in quotes?

I am facing an issue with converting a specific string to JSON format. Here is the string: '{clientId: "1239268108.1505087088", userId: "0.4744496956388684", "url": "http://boomfix.es/", "pageUrl": "1", "timer": "15", "clickCount": "4", "mouseMax": " ...

Finding queries in MongoDB collections seem to be stalling

I have been attempting to create a search query to locate a user by their username. Here is the code: userRouter.get('/user/:user_username', function(req, res) { console.log("GET request to '/user/" + req.params.user_username + "'"); ...

Serve an image in Node.js from a location outside of the public folder

Is there a way to display an image that is located outside of the public folder in my webroot? Here is my directory structure: Webroot --core ----views ----public <- Stylesheets and other images are stored here ------index.ejs <- I want to display f ...

What steps should I follow to generate a JSON object and apply it to refresh an ng-repeat?

Struggling to work this out. I am aiming to craft a JSON object and then utilize it to enhance my ng-repeat (specifically, prepend the ng-repeat with the information contained in the JSON object). Presented below is my code: Javascript: var data1 = &apos ...