Why isn't updating style when ng-class is changed?

In the code below, I am struggling with applying styling based on a dynamic value:

Pug:

div(ng-class="('{{selectedMessageType}}' == 'incoming')?'messageTypeSelected':'messageTypeNotSelected'")

CSS:

.messageTypeSelected{
    background-color: #E8A83C;
    color: #ffffff;
}

.messageTypeNotSelected{
    background-color: #E4E4E4;
}

JS:

$scope.selectedMessageType = 'incoming';
$scope.changeMessageType = function(){
    ($scope.selectedMessageType ==  'incoming')?$scope.selectedMessageType = 'outgoing':$scope.selectedMessageType = 'incoming';
};

The logic to replace {{selectedMessageType}} appears to be correct as per my inspection in the browser's Inspector tool. However, the issue lies in the fact that the styling does not change when the value is updated.

Could you point out any potential errors or improvements in my code?

Answer №1

It is not necessary to use {{}} in the ngClass directive.

Update your code as follows:

<div ng-class="selectedMessageType == 'incoming' ? 'messageTypeSelected' : 'messageTypeNotSelected'"></div>

A functional snippet of code:

(function() {
  angular
    .module('app', [])
    .controller('MainCtrl', MainCtrl);

  MainCtrl.$inject = ['$scope'];

  function MainCtrl($scope) {
    $scope.selectedMessageType = 'incoming';
    
    $scope.changeMessageType = function() {
      $scope.selectedMessageType = $scope.selectedMessageType == 'incoming' ? 'outgoing' : 'incoming';
    }
  }
})();
.messageTypeSelected {
  background-color: #E8A83C;
  color: #ffffff;
}

.messageTypeNotSelected {
  background-color: #E4E4E4;
}
<!DOCTYPE html>
<html ng-app="app">

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
</head>

<body ng-controller="MainCtrl">
  <div ng-class="selectedMessageType == 'incoming' ? 'messageTypeSelected' : 'messageTypeNotSelected'">
    <span ng-bind="selectedMessageType"></span>
  </div>
  <hr>
  <button type="button" value="change" ng-click="changeMessageType()">Change class</button>
</body>

</html>

I suggest you take a look at this tutorial

Answer №2

The ngClass functionality does not follow the format you provided. It should be used in the following way:

ng-class="{'css-style': condition}"

For example, the condition could be isError == true

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

loop not functioning properly with file type input

Having trouble uploading an image and copying it into a folder named images within a loop. Can you assist with solving this issue? Here's my code: $sql="SELECT * FROM product"; $q=$conn->query($sql); while($r=$q->fetch(PDO::FETCH_ASSOC)) { $cod ...

Convert Soundcloud thumbnail into a printable format using the @media print CSS rule

For those wanting to add an embedded Soundcloud player on a blog: <iframe width="500" height="300" scrolling="no" frameborder="no" src="https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/271188615&color=%23ff5500&auto_p ...

The curious date format of /Date(1427982649000-0400)/ is shrouded in

Can anyone help me with converting some date values that I received in a format that is unfamiliar to me? I need to display them on the screen. Here is an example of the format I'm dealing with: /Date(1427982649000-0400)/ The equivalent value in th ...

"Removing the blue initial loader from Filestack during initialization: A step-by-step guide

Currently, I am facing an issue with a button that triggers the filestack uploader in my React application. The functionality works as expected, but I am struggling to override the default blue spinner/loader that is displayed with the filestack uploader. ...

The slider causing conflicts with widgets and content positioned below it in an HTML layout

When implementing a slider with a fade effect, there seems to be an issue with the placement of widgets on the homepage. The problem arises from the margin-top setting as when images change in the slider, the widgets clash with the slider. During the trans ...

Tips for reformatting table row data into multiple rows for mobile screens using ng-repeat in Angular

Just started using Angular JS and I have some data available: var aUsers=[{'name':'sachin','runs':20000},{'name':'dravid','runs':15000},{'name':'ganguly','runs':1800 ...

Animate owlCarousel slide motion in reverse when using the Prev and Next buttons

The default functionality of owlCarousel is to move to the right when clicking Next and to the left when clicking Prev. However, after applying animations, both directions always move in the same direction. Check out this sample on jsfiddle to see the iss ...

Is there a way to update the button's value upon clicking it?

I've hit a roadblock in my tic tac toe game project during class, and I've been struggling for the past two days to get the X's and O's to show up. The deadline for this assignment is tomorrow! Here are the task requirements: COMPSCI20 ...

While attempting to make my div responsive, it unexpectedly became stuck to the navbar

After successfully creating a website that works fine on desktop, I encountered an issue when viewing it on my phone. The main content section, which features jokes, gets scrolled up along with the navbar. I followed a tutorial on YouTube to make the navba ...

The method of utilizing React with Redux to display component properties

I am currently trying to include my common component in my main.js file Successfully implemented this However, when attempting to print my Redux data values in the common component, I created a method called handleClickForRedux to handle this task. Even af ...

unusual actions of $http post request with a specific header

I am working on posting data with headers in AngularJs. If I post data without any header, I can successfully receive the data on the server side. return $http.post('http://localhost:53646/Login', data, { headers: { "Content-Type": "application ...

Node.js refuses to process posts submitted by AngularJS

I have my NodeJS set up on one server and my AngularJS set up on another server. I'm attempting to send data from AngularJS to NodeJS for testing purposes and expect it to be echoed back. However, upon inspecting req.body in my NodeJS code, it always ...

Scaling SVG Graphics in Real-Time

I am currently developing a website where users can interact with an SVG image using textboxes. One of my goals is to make sure the SVG image scales to fit the container div. For example, if the SVG was the same height as the container but only 10 pixels ...

Choose a specific item by its name and retrieve its corresponding identifier using Angular

In my current MVC project using HTML and angular, I am facing an issue with a select list. The list is supposed to be selected based on the name entered in an input box, but unfortunately, I am unable to retrieve the id associated with the selected item. ...

I am attempting to center an image on a webpage while disregarding the margins set on the

Bar.html: <!DOCTYPE html> <head> <link rel="stylesheet" type="text/css" href="customStyle.css" /> </head> <body> The text formatting is spot on. Unfortunately, the following image should be centered, but it's off ...

Tips for removing red borders on required elements or disabling HTML validation

I am on a mission to completely eliminate HTML validation from my project. Although this question suggests that having all inputs inside forms can help, I am using angularjs and do not require a form unless I need to validate all fields in a set. Therefore ...

Incorporate a backdrop to enhance a material icon

I'm working with the following Material Icon code but I want to enhance it by adding a white background for better contrast. Any suggestions on how to achieve this? <a id="lnk_quick_print" href="javascript:;" title="Quick P ...

What could be causing my website to function flawlessly in Firefox but not in Chrome or Internet Explorer?

Hey everyone, I'm feeling lost and have been comparing files using DiffNow. I don't have any code to offer because I'm unsure of where to even begin. The website is coded in php/html/mysql/jquery. Here are my main concerns: -Animations are ...

Changing background color on scroll using jQuery

Looking to create a cool effect where the background color of a fixed header changes as the user scrolls down a full-page block website. Managed to get it mostly working in this Pen, but struggling with determining how much has been scrolled to trigger the ...

How can I reference an html <div> element from an <a href> link within the same html document?

I have a piece of text and I want it to trigger an action when clicked. My code looks like this: <h5>Posted On: {{postedDate | date}} <a href="" style="float:right" >Table Plans</a></h5> When the user clicks on Table Plans, it sho ...