AngularJS: transforming a bound data value

Is there a way to dynamically change the background color of a bound list item based on predefined logic? For example, if a variable is bound to the backgroundColor property and I want to change the color according to some conditions (red for state=0, blue for state=1, and black for state=2).

http://jsfiddle.net/UWqWf/16/

I could manually manipulate the DOM in the click event, but that would result in messy code and require updating $scope.items[x] as well.

Is there a cleaner solution to achieve this?

<ul ng-app ng-controller="MyCtrl">
    <li ng-repeat="i in items" ng-click="toggle()"> <span style="background-color: {{i.state}}"> {{i.name}} </span> </li>
</ul>

function MyCtrl($scope) {
    $scope.items = [{"name":"a","state":"1"},{"name":"b","state":"2"}, {"name":"c","state":"0"}];
    $scope.toggle = function(){
        // toggle the state i.e.
        // if state<3 then state++
        // else state=0 
     };
};

Answer №1

I prefer to separate my styles from my JavaScript code

<style>
.state-0{ background-color: green;}
.state-1{ background-color: yellow;}
.state-2{ background-color: pink;}
</style>

<ul ng-app ng-controller="MyCtrl">
  <li ng-repeat="i in items" ng-click="toggle()"> 
    <span class="state-{{i.state}}">
      {{i.name}}
    </span>
  </li>
</ul>

Answer №2

Have you considered giving this approach a try? You can avoid manual DOM manipulation and instead pass the iteration item directly to the toggle method.

<ul ng-controller="MyCtrl">
    <li ng-repeat="i in items" ng-click="toggle(i)"> 
        <span style="background-color: {{getColor(i.state)}}"> {{i.name}} </span> 
    </li>
</ul>

Additionally, here is an example:

function MyCtrl($scope) {
    $scope.items = [{"name":"Item1","state":1},{"name":"Item2","state":2}, {"name":"Item3","state":0}];
    $scope.color = ["red", "green", "blue"];
    $scope.getColor = function(state){
        return $scope.color[state];
    }

    $scope.toggle = function(item){
          if (item.state<3 )
             item.state++;
         else 
             item.state=0 ;
     };
};

See Demo

Alternatively, you could simplify the code by eliminating the getColor method

 <span style="background-color: {{color[i.state]}}"> {{i.name}} </span> 

View Demo

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 jest mocking a function - it's not functioning as expected

I decided to create a simple test using jest to simulate a date change function. Here is the code snippet: import React from 'react'; import '@testing-library/jest-dom'; import { render, screen } from '@testing-library/react' ...

Struggling to update a Knockout observable array

I'm attempting to send some data to a Knockout observable array. Despite receiving data from my AJAX call without any errors during script execution, I find that the userNames array remains empty when accessed. What could be causing this issue? UserH ...

Retrieving the file name from the line number within the trace stack or Error object

I'm working on enhancing my error handling in Node.js/express. Does anyone know a method to retrieve the filename and line number where an error occurs in my code? error-handler.js, utilizing console.trace, only handles errors at the route level...n ...

Is there a node.js equivalent to Turbolinks available?

One of my favorite features in Rails is Turbolinks, as it enhances the user experience by making pages appear to load faster. Is there any alternative or similar functionality for node.js? ...

Solving Cross-Origin Resource Sharing problem in an Express JS application

I have encountered a CORS error while using this code, despite having applied the necessary cross-origin headers. I am seeking guidance on how to resolve this issue. var express = require('express'); var bodyParser = require('body-parser&ap ...

How can I effectively capture a change in the hour using Node.js?

Do you know of a more efficient way to monitor datetime changes instead of checking every 10 minutes, potentially firing nearly 10 minutes late? Any alternative solutions that I may have overlooked for this issue? ...

Ways to verify if an item is enabled

To ensure a button in my angular application is enabled, I am using Protractor for testing. Here is the test script: it('submit should not be enabled',function() { var price = by.name('price'), oldCategory = by.name ...

Executing two distinct SQL queries within one nodejs function

I'm facing an issue with updating two tables in my database - the stockmaster table and the prodstock table. I've been trying to run a query using a function to update both tables simultaneously, but unfortunately, it's not working as expect ...

Utilizing jQuery Methods within Node.js

Recently delved into the world of node.js and created multiple pages (such as login, signup, blog, etc). If I desire an effect in which: 1. Hovering over the "News" button triggers a slider to appear downwards, To make adjustments to an image within ...

Adding or Deleting Rows from Input Table

I'm in the process of creating a website that features an input table allowing users to easily add or remove rows at their discretion. The desired UI is shown below: https://i.sstatic.net/EFAlM.jpg Here is the HTML code I have developed so far: & ...

Converting form input to JSON and then parsing it into an object

I'm currently working on converting form data to update a JSON object upon submission. Here's my progress so far: var app = { slidePreviews: "", selectedTheme: "", slideDuration: 7000, slides: [] }; $(document).ready(function() ...

When an array object is modified in Vue, it will automatically trigger the get method to validate any

One of the challenges I am facing is related to a button component that has a specific structure: <template> <button class="o-chip border-radius" :class="{ 'background-color-blue': theValue.isSelected, ...

Is there a way to retrieve the automatically generated ID for a document that was created with batch().set in Firestore?

Is there a method to retrieve the automatically generated ID for a document that is created as part of a batch operation in Firestore? Typically, when using .add(), obtaining an ID is straightforward: db.collection('posts') .add({title: &apos ...

Having trouble with the `click()` function not working on a button while using Selenium in

Currently, I am running a selenium test on a remote server in headless mode using the chrome driver. However, when trying to click on a button with the following step, the button does not get clicked. Below is the test step attempting to click the element ...

My issue lies in the execution flow with the child process in Node.js

I've been trying to create a function that takes an input string and returns an output string, but I'm facing challenges due to the delay in response. var result = "initial value"; function executeShell(command) { exec("uname&quo ...

PHP - The variable $_SESSION['var1'] has not been set within the index.php file

My index.php page is causing me some confusion. <?php session_start(); if (!isset($_SESSION['var1'])) { echo "session not started..."; die(); } else { echo "session started"; die(); } ?> Within the page, there is a login form that connec ...

React failed to render the information fetched from an API following a GET request made in componentDidMount()

I recently implemented a function in my React code that calls an API and updates the state based on the data it receives. getUserList() { API.get('/userlist') .then(response => { this.setState({ userLis ...

Ways to conceal an element when it appears in the initial section of a page

I currently have a single-page website consisting of 4 sections which are not scrollable. To navigate between these sections, I have implemented a burger menu button with a fixed position to ensure it remains visible on all sections except the first one. ...

Send the output of MPDF back to the browser by utilizing JSON in combination with ExtJS

I am currently using mpdf to generate a PDF report in my PHP code. I have successfully been able to save the PDF file and view it by using Output($pdfFilePath), but now I need to send it back to the browser using JSON without saving it on the server. To ac ...

Adapt your content to match the current slide of the dynamic Bootstrap Carousel

I recently implemented the basic carousel from the bootstrap website into my web application and encountered a challenge. I want to adjust the content on my site based on the active slide of the carousel... is this achievable? My goal is to display div On ...