What is the best way to apply various styles using the ng-style directive in different scenarios?

When working in Angular, I am attempting to apply different style attributes based on varying conditions. However, the typical conditional expression method is limited to just two conditions and is not providing the desired results.

<div ng-style="
    (status=="up")  ?{'background-color':'green' ,'color':'green'}
    (status=="down")?{'background-color':'red'   ,'color':'red'}
    (status=="idle")?{'background-color':'yellow','color':'yellow'}
    (status=="")    ?{'background-color':'grey'  ,'color':'grey'}
">

It would be more convenient if there was a way to pass attributes to a function that returns a style object for ng-style, like the following example which strangely is not functioning correctly!

$scope.styleFn(status,attr) {
        (status=="up")  ?{attr:'green'}
        (status=="down")?{attr:'red'}
        (status=="idle")?{attr:'yellow'}
        (status=="")    ?{attr:'grey'}
}

<div ng-style="styleFn('up','background-color')">

Answer №1

A more intricate condition can be specified using a function.

var style = {
  'up': {'background-color':'green' ,'color':'green'},
  'down': {'background-color':'red' ,'color':'red'},
  'idle': {'background-color':'yellow' ,'color':'yellow'},
  'default': {'background-color':'grey'  ,'color':'grey'}
}

$scope.applyStyle = function(status) {
    //the status is the key to retrieve the desired style
    return status ? style[status] : style['default']; 
)};

next, add it to the template

<div ng-style="applyStyle(status)"></div>

Answer №2

If you want to apply different styles using ng-class, that can be done as well.

function DemoCtrl($scope) {
    $scope.status = 'up'
}
.green {
    color: green;
    background-color:green;
}
.red {
    color: red;
    background-color:red
}
.yellow {
    color: yellow;
    background-color:yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app>
    
    <table ng-controller="DemoCtrl">
        <tr ng-class="{'green': status == 'up','red':status== 'down' ,'yellow': status== 'idle' } ">
            <td style="color:white;">Your status is {{status}}</td>
        </tr>
    </table>
</div>

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

Do specific href values need to be specified for document.links to return links?

Is there a shortcut to create an array of links in JavaScript without using a loop? var links = document.links; Instead of looping through the array to find elements with href attribute equal to '/somehref', is there a way to directly filter th ...

Angular 7 - Customize Mat-select-value color depending on a specific condition

One issue I am facing is changing the color of a selected value in a mat select based on a condition. This change should be visually apparent to the user. Although accessing mat-select-value from the styles is possible, implementing a condition using ng-cl ...

Display your StencilJs component in a separate browser window

Looking for a solution to render a chat widget created with stenciljs in a new window using window.open. When the widget icon is clicked, a new window should open displaying the current state while navigating on the website, retaining the styles and functi ...

What is the best method for dynamically binding Tailwind classes in VueJS3/NuxtJS3?

Is there anyone who knows how to correctly bind the content Tailwind class dynamically in Vue.js 3/Nuxt.js 3? Let's say we have const isExpanded = true <h1 :class="{'after:content-[`:`]' : isExpanded}">Hello</h1> I att ...

Validating data for Telegram Web Bots using JavaScript

Struggling with creating a user verification script for my Telegram web app bots. Need help troubleshooting. import sha256 from 'js-sha256' const telegram = window.Telegram.WebApp const bot_token = '<bot-token>' const data_check_ ...

The links located beneath the iframe/span element are unclickable

My latest creation is a static advert ticker positioned at the bottom of the window. It's contained within an <iframe> for easy placement on other websites. I added a <span> around the <iframe> to keep it fixed at the bottom of the s ...

dc.js bar graph bars blending together

This datetime barChart is causing me some trouble. Interestingly, when I try to replicate the issue in a fiddle (check here), everything functions as expected. Please note that the data takes about 30 seconds to load from github. Below is the code for the ...

What is the process of including a pre-existing product as nested attributes in Rails invoices?

I've been researching nested attributes in Rails, and I came across a gem called cocoon that seems to meet my needs for distributing forms with nested attributes. It provides all the necessary implementation so far. However, I want to explore adding e ...

Expanding the last row to ensure its proper width with flex-grow

I have a flexbox with columns that each take up one third of the width. However, due to using flex-grow, the last element does not stick to its column size. I understand why this is happening, but I don't want to use max-width as it's not always ...

"How to ensure consistent styling for all buttons, including dynamically created ones, in an application by utilizing the jQuery button widget without the need for repetitive calls to

Hello everyone, I am a newcomer to stack overflow and I have a question to ask. Please excuse any errors in my query. I have searched for an answer but have not been successful in finding one so far. Let's say I have a webpage where I am using the jQ ...

Utilizing Next.js routing to accommodate two distinct subdomains on a single website

I am looking to develop a new platform using Next.js (React.js and React-router). The platform will have two distinct spaces - one for users and another for the owner to manage all users. To achieve this, I plan on splitting both areas into two subdomains: ...

Deleting query strings from the URL - HashRouter

In my application, I have a LoginContainer component that houses both a login-form and a signup-form. These components are displayed on the same page, with only one of them being rendered based on user interaction. While the functionality of the forms is ...

Extract data from the Ajax database and automatically hide the "Load More" button when all items

Every time I fetch data from my MySQL database, I retrieve 5 items at once. $query = $pdo->prepare("SELECT * FROM names WHERE id < ? ORDER BY id DESC LIMIT 5"); $query->execute([$_POST["id"]]); while($row = $query -> fetch() ...

Issue with Angular Route Guard - Incorrect redirection to login page

I'm encountering an issue with my Angular app where even after the JWT token has expired, I am still able to navigate within the application without any API data being accessible. I've double-checked my setup and it seems right, but for some reas ...

Issue with retrieving Combobox value within AngularJS ng-repeat generated table using ng-model

Here is my code that I need help with: <thead> <tr> <th>Id Detalle_Venta</th> <th>Id Producto</th> <th>Producto </th> <th>Cantidad </th> <th>Direccion </th> ...

Achieving Compatibility Between jQuery 3.6.0 and Node.js v12.16.1

Utilizing an online IDE known as Replit, I am working on node.js projects running on the node version: 12.16.1. However, my current challenge lies in attempting to make jQuery 3.6.0 compatible with this particular node.js version. Despite trying various me ...

Transferring a JSON document to an Express server with JavaScript

I've recently started learning JavaScript and I'm facing an issue with sending a JSON file to my server (Express) so that I can parse its contents and use them in the web application I'm developing. Here's my current setup: a JSON fil ...

Tips for adding jQuery UI styling to elements generated dynamically

I have a challenge with generating text fields using jquery while applying jquery ui styling to the form. The issue is that the dynamically created elements do not inherit the css styles from jquery ui: let index = 0; $('#btn_generate').on(& ...

How to Delete Elements from an ngList Array in Angular

I encountered an issue while utilizing ngList in a text box to exchange data with my server. The problem arises when I attempt to delete items from the generated array directly, as it does not reflect the changes in the input field. The main concern is th ...

Navigating the world of getElementById and addEventListener outside of the DOM

Having some dynamic HTML code in my JS, I'm hoping to assign an ID to a particular tag: content: ` <p id="openKeyboard"> If the click happens, I want to trigger an event. </p> ` However, upon ...