Adjust the color of each list item depending on an array of strings

Within my perspective, I possess a collection of different statuses.

<ul>
    <li>FIRST_STATUS</li>
    <li>SECOND_STATUS</li>
    <li>THIRD_STATUS</li>
</ul>

To continuously update the statuses in my controller model, I use the following function:

    $interval(function () {
            $scope.bad_statuses = Model.getStatuses({id: $scope.someModel.id});
    }, 1000);

The $scope.statuses array contains the list of bad statuses, such as $scope.bad_statuses[0] = FIRST_STATUS. If a status exists within $scope.bad_statuses, I want to color it red; otherwise, it should be green.

In essence, I need to extract each value from the <li> elements and based on whether it is present in the $scope.bad_statuses array, assign either a red or green color.

How would you suggest tackling this issue? I am new to AngularJS.

Answer №1

Here is a plunkr that should solve your issue :)

https://plnkr.co/edit/OP66yUB5lxBS5uCmtbRh?p=preview

Check out the JavaScript code below:

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope, $interval) {
  $scope.name = 'World';
  $scope.bad_statuses = ["FIRST_STATUS", "THIRD_STATUS"];
  $interval(function () {
            var lis = document.getElementById("list").getElementsByTagName("li");
            angular.forEach(lis, function(value, key){
               if($scope.bad_statuses.indexOf(value.innerHTML) > -1){
                 console.log("red");
                 value.style.color = 'red';
               }
               else{
                 console.log("green");
                 value.style.color = 'green';
               }
            });

  }, 1000);
});

Answer №2

<li ng-style="updateColor(*status*)"></li>

In the script:

$scope.updateColor = function(status) {
    return $scope.bad_statuses.indexOf(status) > -1 ? {color: 'red'} : {color: 'green'};
}

Explore more about the ng-style directive 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

I am currently working on creating a system for displaying rating stars for products. The rating value, which ranges from 0 to 5, has already been provided

class PostBodyRatingStars extends React.Component { render() { const { classes } = this.props var rating = this.props.rating function createMappingArray(rating) { var arr = [] for (i = 0; i < 5; i++) { if (rating >= ...

Change the input field to uppercase using JavaScript but do not use inline JavaScript

Hey there! I have a basic script set up (see below) with an input field allowing users to enter a query. This query is then sent to a socrata webservice to request specific data, which is displayed in an alert box. So far, everything works smoothly. var l ...

Troubleshooting a dysfunctional Vue.js component

I am currently facing a challenge in getting components to function properly. Interestingly, without the component, everything seems to be working fine (as per the commented code). Here is my HTML snippet: <strong>Total Price:</strong> <sp ...

Implement an event listener on the reference obtained from the React context

Within the React context provider, a ref is established to be utilized by another component for setting a blur event listener. The issue arises when the blur event fails to trigger the listener. The following is a snippet of code from the context provider ...

The way an event can be outrun or vanish due to another event

let bar = new function(){ $scope.MessageSpan="Item added successfully";} When the Add button is clicked, the above function is invoked. However, if I want to hide this message when any other button is clicked, I would have to update the span text for all ...

One-of-a-kind browser identification for users, no login required

I have an online boutique and I want to enable customers to make purchases without creating an account. To achieve this, I need a way to associate a selected list of items with a user. Initially, I considered using the IP address for this purpose but fou ...

Issues with Implementing Scroll Directive in Angular JS

Apologies for asking what may seem like a silly question. I'm still new to using AngularJS and recently came across a neat little scroll directive on http://jsfiddle.net/88TzF/622/. However, when I tried implementing the code in the HTML snippet below ...

Need help with functions in JavaScript?

I'm struggling with understanding some code related to javascript and angularjs. I came across this line - !function(a,b,c){}(x,y,z) - and I can't make sense of it. It's something new to me and I would appreciate any help in clarifying its p ...

Update a portion of a hyperlink using jQuery

Currently, I am utilizing Ransack for sorting purposes. However, I encountered an issue when attempting to modify the sorting links in cases where both search and sorting functionalities are implemented using AJAX. As a result, I have taken it upon myself ...

Efficiently Loading AJAX URLs using jQuery in Firefox

setInterval(function(){ if(current_url == ''){ window.location.hash = '#!/home'; current_url = window.location.hash.href; } else if(current_url !== window.location){ change_page(window.location.hash.split('#!/&apo ...

Using jQuery to target a specific item from a retrieved list of elements

I'm currently working on a photo gallery feature that is reminiscent of Instagram or Facebook user photos. My goal is to enable users to view details about each image (such as the date) in a box that appears over the image when they hover over it. E ...

Verify the visibility of the toggle, and eliminate the class if it is hidden

I have implemented two toggles in the code snippet below. I am trying to find a solution to determine if either search-open or nav-open are hidden, and if they are, then remove the no-scroll class from the body element. $(document).ready(function() { ...

Why do confirm or alert boxes in Safari on Windows require a double click?

I'm currently working on a simple JavaScript example where I want to display an alert box when an HTML button is clicked in SAFARI. However, I've noticed that it requires a double click to make the alert disappear from the screen. Does anyone ha ...

What is the best way to sort ISO DateTime objects that fall outside of a particular time frame?

I'm currently working on a project that involves a list of objects with properties for startTime and endTime, all in ISO format. Here's a snippet of the list: list = [ { startTime: '2022-06-26T10:00:00.000Z', endTime: '2022- ...

Utilizing Angular 2's offline capabilities for loading locally stored JSON files in a project folder

I've been attempting to load a local JSON file from my Angular 2 project folder using the HTTP GET method. Here is an example of the code snippet: private _productURL = 'api/products/products.json'; getProducts(): Observable<any> ...

The React Material UI Autocomplete, when combined with React-window, causes the list to re-render at the top

Looking for some assistance with React since I'm new to it. Having trouble with the Material-ui autocomplete component and need help from experienced React developers. The issue I'm facing is that when I choose an option from the autocomplete dr ...

Dividing JSON information into parts

I am attempting to present a highchart. I have utilized the following link: Highchart Demo Link Now, I am trying this web method: [WebMethod] public static string select() { SMSEntities d = new SMSEntities(); List<str ...

combining multiple arrays at once in angularjs

When utilizing ng-repeat with values group1 and group2, I encountered the following output: grp1 grp2 abc def value1 value2 However, I am aiming for the following structure: grp1 abc value1 grp2 def value1 HTML: <ul ...

Why isn't CSS showing up in preview mode on the network tab?

I have been using nextjs for server-side rendering and I am encountering an issue where my CSS class is not being applied on the preview tab, it only works on the client side. Any idea why this is happening? Here is the code snippet: https://codesandbox.io ...

Unable to locate the module model in sequelize

Having some trouble setting up a basic connection between Postgres and SQL using Sequelize. I keep getting an error where I can't require the model folder, even though in this tutorial he manages to require the model folder and add it to the sync, lik ...