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

Having trouble with Angular 2 Routing and loading components?

I am facing an issue with Angular 2 where it is searching for my component in app/app/aboutus.component, but I cannot pinpoint the source of the problem. Here is my app.component.ts code: import { Component } from '@angular/core'; import { ROUT ...

How to format values in a textarea using AngularJS

Is there a way to address the following issue without replacing \n with other values? A user can input a description for something in a textarea and include line breaks. In the controller, there is a value called description which includes a string ...

What is the process for printing with JQuery?

I have nested divs with dynamically generated images in my HTML code. My problem is that when I click the print button, I want the corresponding image to be printed. <div id="outputTemp" style="display:none"> <div id="rightoutputimgae"> <di ...

What is the best way to implement a switch that can simultaneously display both the on and off positions?

I need help customizing a toggle switch element in CSS. I want the first row to display as on (blue color) and the second and third rows to be displayed as off or grey. So far, my attempts to modify the CSS code have been unsuccessful. .switch { posi ...

Ajax sends the URL location to Python

I'm attempting to piece together some code. There are two distinct functions that I am trying to merge into a single entity. Code snippet: <!DOCTYPE html> <head> <meta http-equiv="content-type" content="text/html;charset=UTF-8"> &l ...

What are the hours available on the Angular DatePicker?

Can I customize the angular datepicker to only display hours and not minutes or dates? I am aware that I can use the following code: <div class="ng-isolate-scope" view="hours" date-picker="start"></div> However, is it possible to exclude the ...

Using a diverse class for enhancing the PrimeVue dialog's maximizable feature

I'm currently working with the PrimeVue Dialog component. My goal now is to apply different styles depending on whether the dialog is maximized or not. Let's keep it simple by saying I want to change the text to bold or red when the dialog is max ...

Is the for loop programmed to stop at the first match?

I've been working on filtering a txt file using nodejs. Here's my code snippet: const fs = require('fs') let list = fs.readFileSync('./newmR.txt', 'utf-8').split('\r\n') console.log(list.length) ...

Tips for implementing owl carousel in Nuxt.REACT_UNITS_CODIFY

Is there a way to make the script function on every page without the need for these pages to be reloaded? I have the Owl Carousel script in my static folder, and I have already included it in nuxt.config.js as shown below: head: { title: 'title&ap ...

Ensure that only the most recent Ajax request is allowed

In my project, I have an input box that triggers an ajax request with every key press. This means if I type the word "name," there will be a total of 4 requests sent out. However, what I really need is to only execute the latest request. So even if I enter ...

Encounter the "Error: Source 'cloudsTileLayer-RasterSource' not found" message while trying to integrate a weather tile layer into Azure Maps

I have been working on a React application that utilizes the React-Azure-Maps npm package. My current challenge involves creating a weather layer, which I believe shares similarities with the sample code provided for layers. The code snippet responsible f ...

Encountering difficulties in loading my personal components within angular2 framework

I encountered an issue while trying to load the component located at 'app/shared/lookup/lookup.component.ts' from 'app/associate/abc.component.ts' Folder Structure https://i.stack.imgur.com/sZwvK.jpg Error Message https://i.stack.img ...

The automated test locator in Angular using Protractor is failing to function

I am facing a challenge with my angular web application as there are some elements that are difficult to interact with. One specific element is a checkbox that needs to be checked during testing: ` <div class="row form-group approval_label"> < ...

The functionality of JQuery's .hover() is disabled once an HTML onClick() event is activated

I am currently working on a webpage and attempting to incorporate JQuery into it for the first time. However, I seem to be encountering some issues that I believe might have simple solutions. Background Information My JQuery code only contains one event l ...

`Can't figure out how to input variables into PHP Form`

As a newcomer to PHP, I apologize if this question seems obvious. I would like to create a form that gathers more information than just the typical "name," "email," and "message." I am specifically looking to include the following labels: (i) Will you be ...

When fetching data from the API in Angular, the response is displayed as an object

After fetching data from the API, I am encountering an issue where the "jobTitle" value is not displaying in the table, but instead appears as an array in the console. Can someone assist me with resolving this problem? Below is the visibility.ts file: exp ...

Configuring CORS in an Angular JS controller

Having a controller with a service that retrieves JSON from another server, I encountered the following issue: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http:somesite.com. This can be fixed by moving the ...

The choice between using "npm install" and "npm install -g" for

New to the world of node, and feeling a bit lost when it comes to all this "install" stuff. Could someone clarify for me, what sets apart install from install -g? If something is installed with install -g, can it be accessed from anywhere, or is it restr ...

Unlocking the Power of $http and Stream Fusion

I'm interested in accessing the public stream of App.net. However, when I attempt to retrieve it using a simple $http.get(), I only receive one response. $http .get('https://alpha-api.app.net/stream/0/posts/stream/global') .success(func ...

Is there a way to implement multiple "read more" and "read less" buttons on a single page?

I am currently working on a rather large project and I am encountering some issues with the read more buttons. As someone who is fairly new to JavaScript, I am still grappling with the concepts. While I have managed to make the function work for the first ...