Tips for implementing a dynamic value in the ng-style based on certain conditions

Is there a way to set a background-color conditionally using ng-style when the color value can be updated from $scope?

These are the variables in my scope:

$scope.someone = { id: '1', name: 'John', color: '#42a1cd' };
$scope.mainId = 1;

Currently, I am setting the background color without any conditions like this:

<div ng-style="{'background-color': someone.color}">
    {{someone.name}}
</div>

I want to apply this background color only when someone.id == mainId. I have tried multiple solutions but none of them seem to be correct:

  • ng-style="{{someone.id == mainId}} ? ('background-color': {{someone.color}}) : null"
  • ng-style="{ ('background-color': someone.color) : someone.id == mainId }"

Check out JSFiddle demo for testing

If anyone has an idea on how to achieve this, please let me know!

Answer №1

It appears to be functioning correctly.

ng-style="{'background-color': user.identifier === primaryId ? user.selectedColor : ''}"

Check out the revised demo with two users - the one with primaryId is highlighted with a background color, while the other one remains unaffected: http://jsfiddle.net/abc123de/9/

Answer №2

Here is a possible solution:

<div ng-app="myApp" ng-controller="MyCtrl">
  <div ng-style="{'background-color': getColor(someone)}">
    {{someone.name}}
  </div>
</div>

var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', ['$scope', function($scope) {
  $scope.someone = {
    id: 1,
    name: 'John',
    color: '#42a1cd'
  };
  $scope.getColor = function(someone) {

        if($scope.mainId === someone.id) {
        return someone.color;
      }
  }
  $scope.mainId = 1;
}]);

Answer №3

If you want to achieve this effect, you can use the following code snippet:

ng-style="someone.id == mainId ? {'background-color':'{{someone.color}}'} : {'background-color':'red'}"

To see a live example, check out the updated fiddle at http://jsfiddle.net/fgc21e86/9/

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

`Can you guide me on the proper path for designing this website layout?`

As I embark on creating my first website, I have a specific vision in mind. I want the full display on a computer screen to show all the information and links without any need for scrolling. However, when the window is resized to smaller screens, I would l ...

Having trouble loading a React component

I've been working on breaking down modules from a monolithic React project to store them separately in my npm registry. However, I'm encountering issues with exporting and importing them correctly. Previously, I was using the following code: con ...

Divide the inner HTML content to extract text for translation purposes using JavaScript

I am currently developing an application that requires extracting the innerHTML of Body, then extracting the text in a JSON format. This JSON will be used for translation, and the translated JSON will be used as input to recreate the HTML markup with trans ...

Utilizing jQuery to Extract Values from a List of Options Separated by Commas

While usually simple, on Mondays it becomes incredibly challenging. ^^ I have some HTML code that is fixed and cannot be changed, like so: <a class="boxed" href="#foo" rel="type: 'box', image: '/media/images/theimage.jpg', param3: ...

Click here to navigate to the same or a different page using an anchor

I'm currently implementing this code: $(function() { $('a[href*=#]:not([href=#])').click(function() { if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostna ...

React: maintaining referential equality across renders by creating closures with useCallback

I want to make sure the event handling function I create in a custom hook in React remains referentially equal across renders. Is it possible to achieve this using useCallback without specifying any variables it closes over in the dependencies list? Will o ...

What is the process for including parameters in a javascript/jquery function?

This unique script enables you to click on a specific element without any consequences, but as soon as you click anywhere else, it triggers a fade-out effect on something else. Within the following code snippet, you can interact with elements inside $(&apo ...

Customizing the choices for an ActionSheet on Ionic 2 on the fly

After making a GET request, I receive JSON data containing an array of options with id, style, and name for each element. I need to dynamically populate the options in my ActionSheet within my Ionic 2 app based on this API response. The ActionSheet is fu ...

Display a message if the local storage is empty

Recently, I came across a javascript code snippet that is designed to save birthday data in local storage and then display the data within a div element. The current functionality only shows nothing if the storage is empty. However, I require it to display ...

Error: 'require' is undefined in react.production.min.js during production deployment

Greetings! I am encountering some difficulties while trying to build on production: the error "require is not defined" is being caused by react.production.min.js. Below are my webpack.config.js and package.json files: webpack.config.js const path = requi ...

Confirm the input validity using jQuery for radio buttons, checkboxes, and dropdown menus

When it comes to validating input fields like text, email, radio, checkbox, and select, I have the following structure in my form: <fieldset> <div class="form-top"> <div class="form-bottom"> <div class="for ...

It appears that my array is not being properly populated by my callback functions

I am encountering an issue with my callback functions. The objective of my code is to send 16 GET requests to a REST API in order to retrieve 16 distinct JSON files. These JSON files are then supposed to be converted into dictionaries representing the foot ...

Chromium is having issues with updating the dynamic source attribute

One portion of my script that pertains to the question is as follows: <script type="text/javascript> function handleImageClick() { var image = $("#image_id"); $(image).attr("src", "ajax-loader.gif"); $.ajax({ ...

Utilizing variables in Angular service to make API calls

Currently, I am working on accessing the Google Books API. Initially, I was able to directly access it in my controller but now I want to follow best practices by moving the business logic into a directive. HTML <form ng-submit="search(data)"> < ...

The command `sequelize.sync({force:true}) is running into issues and the log output is coming up empty

I encountered a multitude of questions while working on this particular issue. None of them seemed to have the same problem, and after 20 straight hours of trying to solve it, I'm feeling quite stressed. So, I apologize if I missed a similar issue. Th ...

Struggling with removing the unattractive left border on my Tumblr page

I am currently working on the website www.fashiontogo.ca To see the source code, please use Google Chrome's feature to view the source since I cannot provide the HTML or CSS directly here. The site is not my own creation, and I did not develop it fro ...

Having a tough time navigating the Bootstrap upgrade from 2.x to 3.x - now my design is all out of whack

Upgrading my site to the newest version of Bootstrap has been quite the challenge. I'm noticing that despite the window size being the same, version 1 and version 2 of my site are displaying different @media sizes. What's going on? On the left i ...

Is there a way to set up gulp without relying on npm when using shared hosting?

While working on my shared hosting, I encountered a roadblock regarding the installation of gulp for compiling LESS assets into CSS. The hosting administrator has declined to install npm, which is essential for setting up gulp. Given this limitation, I am ...

What is the best way to replace multiple strings with bold formatting in JavaScript without losing the previous bolded text?

function boldKeywords(inputString, keywords){ for (var i = 0; i < keywords.length; i++) { var key = keywords[i]; if (key) inputString= inputString.replace(new RegExp(key, 'gi'), '<strong>' + ...

Issue with Checkbox Functionality Between Parent and Child Components in React.js

In the main component, I have four checkboxes. My goal is to display a value from a function in the child component based on whether each checkbox is checked or not. export default class App extends Component { constructor(props) { super(props); ...