Utilizing Angular's JSON model to style CSS elements

Recently, I came across some generated code within the application that looks like this:

"PHcolour":"rgb(4, 31, 156)","Ctextcolour":"rgb(59, 214, 252)"

I have successfully retrieved the data from the model using curly brackets {{CtextColour}},

My goal is to implement a button on the page that can alter the color scheme of the website. I have achieved similar functionality using ng-click for other features.

The current challenge I am facing is that CSS does not recognize the use of {{}}. My attempted approach was as follows:

<style media="screen">
.custom { background-color: #fff; }
.custom h1 { color: {{Ctextcolour}}; }
.custom h2 { color: {{Ctextcolour}}; }
.custom h3 { color: {{Ctextcolour}}; }
.custom h4 { color: {{Ctextcolour}}; }
.custom h5 { color: {{Ctextcolour}}; }
.custom h6 { color: {{Ctextcolour}}; }
.custom p { color: {{Ctextcolour}}; }
.custom th { background-color: #c3cced; color: {{Ctextcolour}};}
.custom.panel-heading { background-image:-webkit-linear-gradient(top, #c3cced, #c3cced ) !important; color: {{Ctextcolour}} !important;}
</style>

This method did not work and even caused the rest of my HTML code to turn pink in my IDE (Atom).

Switching to the following structure removed the pink coloration, but still did not yield the desired result:

<ng-style media="screen">
.custom { background-color: #fff; }
.custom h1 { color: {{Ctextcolour}}; }
.custom h2 { color: {{Ctextcolour}}; }
.custom h3 { color: {{Ctextcolour}}; }
.custom h4 { color: {{Ctextcolour}}; }
.custom h5 { color: {{Ctextcolour}}; }
.custom h6 { color: {{Ctextcolour}}; }
.custom p { color: {{Ctextcolour}}; }
.custom th { background-color: #c3cced; color: {{Ctextcolour}};}
.custom.panel-heading { background-image:-webkit-linear-gradient(top, #c3cced, #c3cced ) !important; color: {{Ctextcolour}} !important;}
</ng-style>

The HTML markup for the button is as follows:

<button type="button" class="btn btn-info" ng-click="colorScheme = 'custom'" ng-model="eventData.theme">Custom Theme
    </button>

Upon inspecting the element, it was evident that no changes had been applied to the button. Furthermore, there were no JavaScript errors detected.

Thank you for your assistance.

Edit http://plnkr.co/edit/8V35DqflzX9pkFcmpesb?p=preview

Answer №1

Check out the official documentation page for ngStyle. Here's a demonstration of how it can be utilized:

HTML

<p ng-style="myStyle">Text</p>
<button ng-click="set()">set</button>
<button ng-click="clear()">clear</button>

Controller

$scope.data = {"PHcolour":"rgb(4, 31, 156)","Ctextcolour":"rgb(59, 214, 252)"};

$scope.set = function(){
    $scope.myStyle = { color: $scope.data.Ctextcolour } 
};

$scope.clear = function(){
    $scope.myStyle = undefined; 
};

View plunker example.

Answer №2

ng-style is a useful feature in AngularJS that functions similarly to HTML style attributes, allowing you to add properties directly to an element. However, it does not enable the generation of new CSS classes.

To learn more about ngStyle, refer to the official documentation.

You may find this post helpful, and I have included an example snippet for your reference:

<!doctype html>
<html lang="en" ng-app="myApp">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>

  <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootswatch/3.0.0/united/bootstrap.min.css">
  
  <style>
    .original {
      background-color: red;
    }
  </style>

  <script>

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


  myApp.controller("myAppCtrl", ["$scope", "$document", function($scope, $document) {

      $scope.colors = ['#C1D786', '#BF3978', '#15A0C6', '#9A2BC3'];

      $scope.style = function(value) {
          return { "background-color": value };
      }

  }]);


  </script>

</head>
<body>

<div ng-controller="myAppCtrl">
 <h4 class="original" > hi! i have the original class</h5>
    
  <h4 class="original" ng-style="style(colors[0])"> hi! i am the first color in array</h5>
  <h4 class="original" ng-style="style(colors[1])"> hi! i am the second color in array</h5>


</div>

</body>
</html>

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

AngularJS - where each client maintains their own MongoDB database

After spending hours on this task, I'm still struggling to find a solution. I have a mean stack application that caters to multiple clients, and I am looking to assign each client their own database. Is this possible? For Example var client_name = ...

Is it possible to apply a styling to a table data cell based on the table header relationship

Let's say I have a table header with content like this... <th> <div class="text-left field-sorting " rel="local_inventory"> Local inventory </div> </th> <th> <div class="text-left field-sorting " rel="something el ...

Expanding the CheckBoxList Labels' width to full width in order to enable row selection

This question may seem straightforward, but I have not been able to find a specific answer here or through Google search. Within an ASP.Net CheckBoxList, I have a dropdown selection list implemented using an overlaid div. The default HTML generated for t ...

What is causing the size increase animation to not work properly with ngShow in AngularJS?

I'm looking to animate the height of a dropdown menu using max-height. It's mostly working, but when it expands, the transition is not smooth. However, when I shrink it back down, the transition works fine. You can check out the demo for the HTM ...

restructure array upon alteration of data

Here's the current structure of an array stored in a $scope variable: $scope.objects: [ {selected: true, description: 'string1'}, {selected: false, description: 'string2'}, {selected: true, description: 'string3'}, ...

"Modifying the form-control-lg class in Bootstrap and AngularJS affects input size exclusively, leaving the label unaffected

Currently, I am focusing on enhancing an AngularJS custom text input component: <div class="form-group has-feedback" ng-class="[$ctrl.sizeClass, {'has-error': $ctrl.isNotValid(), 'has-success': $ctrl.isValid()}]" > ...

What is the most effective way to transfer color values from one div to another?

When recreating a game similar to Mastermind, I encountered a challenge of copying color values from one div to another upon clicking a button. Despite browsing the web, I haven't found a solution for this specific situation. Below is the code I have ...

Retrieving Twitter posts using the screen_name parameter in a Node.js environment

I am looking to create a website that allows users to enter the Twitter screen name of any celebrity. When the user clicks on the "show tweet" button, the latest tweet from that screen name will be displayed. I am interested in implementing this feature ...

Two ng-click events are triggered within a nested ng-click

I am facing an issue with using the ng-click within a nested list under another list that also has a ng-click event. Here is my code snippet: <ul> <li ng-repeat="facet in node.Facets" ng-click="updateNav(facet.Action)" ng-cloak & ...

I am unable to make any changes to the CSS in the WordPress code that is already integrated

I have created a static web page to serve as my primary homepage. The page is built using HTML and CSS, with some PHP code pulled from My WordPress integrated into it. One of the functionalities I've added is to display the three most recent posts on ...

Unable to properly align Font Awesome icons

I am facing an issue with the alignment of some divs that contain a Font Awesome icon with a circle around them. The problem is that they are not aligned correctly due to varying widths, causing the text to be misaligned vertically. Is there a way to fix ...

If the text is too lengthy, enclose it within a div element

I am facing an issue with a fixed width DIV of 300px. Within this DIV, I have dynamic text that sometimes exceeds the width and gets cut off. Is there a way to make the text wrap when it exceeds the 300px limit without increasing the height of the DIV? Is ...

Save updated tags only when the form is submitted in ngTagsInput

Can the sending of a new tag to the server be disabled after adding it to the input and saving it later by clicking a submit button? This is my Controller: vm.tags = []; $scope.loadTags = function (query) { return $http.get('api/tags?query=' ...

Adjusting the spacing between characters in SVG text elements

Take a look at this unique SVG: <svg xmlns="http://www.w3.org/2000/svg"> <defs> <style type="text/css"><![CDATA[ .code { font-family: monospace; white-space: pre; tab-size: 4; } ]]></style> </defs> <text class="cod ...

Tips for changing a specific item within an ng-repeat loop in AngularJS

Here is my HTML code: <tr ng-repeat="customer in customers"> <td> {{customer.customer_name}} </td> <td> {{customer.mobile}} </td> </tr> Upon executing this code, I receive 3 <tr>...</tr> blocks as s ...

What is the best way to ensure a navigation bar remains fixed at the top of a webpage?

My goal is to create a navigation bar that remains at the top of the page much like how it appears on forbes.com I am aware that I can achieve this by using the following CSS: nav { position: fixed; top: 0; } However, in my case, the navigation ba ...

Troubleshooting a product grid problem in an online store's website

How do I address the issue displayed in the image using CSS (I'm new to CSS/HTML)? The problem is that when the product label is too long, the add button slides down. And if the label is short, it slides up. Below is the CSS and HTML code: <div ...

How to import a template from a different webpage in AngularJS

I have a situation where I need to include a template from one HTML page into another because they are both lengthy and it's not practical to keep them on the same page. Therefore, I have decided to separate them for better organization. Here is an ov ...

Horizontally align the label with the Checkbox

Hi everyone, I'm new to this forum and I've encountered a problem that I am struggling to resolve. The issue lies with a table containing a checkbox list. Initially, everything looks fine when I use: display:inline-block; However, on small ...

The form submission did not yield any results

function calculateCost() { var projectorCost=0,price=0,quantity=0,discountPrice=0,totalCost=0; var modelName=document.getElementById('projectormodel').value; var quantity=document.getElementById('q ...