The color of ngClass does not update according to the variable's value

When the value is true, I want to display a green text message and when it's false, I want it to be red.

This is my angular app:

In the controller, I declare a variable at the beginning and set it as true:

$scope.IsColor = true;

if (response.data.indexOf("Panelists successfully added") !== -1) {
    $scope.IsColor = true;
    $scope.Messages = response.data;                            
    angular.element("#msg").focus()
    return true;
}
else {
    $scope.IsColor = false;
    $scope.Messages = response.data;
    angular.element("#msg").focus()                           
    return false;
}

In HTML:

<div id="msg" ng-repeat="msg in Messages" ng-style="IsColor && {'color':'green'} || {'color': 'red'}">{{msg}}</div>

Despite the response being positive or negative, the text always shows up in red.

Can anyone figure out what the issue might be here?

Thank you, Erasmo

UPDATE

Additional html

<body>
    <div class="container pt-5 pb-5">
        <div class="row">
            <div class="col-md-8">
                <div ng-app="MyApp" ng-controller="MyController">

                    <div>
                        <input type="button" value="Upload" id="btn-upload" ng-click="Upload()" />
                    </div>

                    @* Excel Contents Table *@
                    <table class="table mt-4 mb-5" id="tblPanelists" ng-show="IsVisible">
                        <tr>
                            <th>Name</th>
                            <th>Email</th>
                        </tr>
                        <tbody ng-repeat="p in Panelists">
                            <tr>
                                <td>{{p.Name}}</td>
                                <td><a href="mailto:{{p.Email}}">{{p.Email}}</a></td>
                            </tr>
                        </tbody>
                    </table>
                    <div id="msg" ng-repeat="msg in Messages" ng-style="IsColor && {'color':'green'} || {'color': 'red'}">{{msg}}</div>
                    <div class="mt-3">
                        <button type="submit" class="btn btn-admin-blue" id="btn-add-panelists" ng-click="AddPanelists()"
                                ng-disabled="disableSubmit">
                            Submit
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>

and the angularjs controller-function Add Panelists

The $scope.IsColor boolean is declared outside of the AddPanelists function within the controller and used inside the AddPanelists function.

AddPanelists function:

$scope.AddPanelists = function () {
        $scope.arr = new Array;
        angular.forEach($scope.Panelists, function (item) {
            var b = {
                name: item.Name.trim(),
                email: item.Email.trim()
            };
            $scope.arr.push(b);
        });
        if ($scope.webinarId !== '') {
            if ($scope.arr.length > 0) {
                var data = JSON.stringify({ 'panelists': $scope.arr, 'webId': $scope.webinarId.split(' ').join('') });
                //Call the services
                $http.post('/meetings/panelists/home/createpanelists', data)
                    .then(function (response) {
                        if (response.data.indexOf("Panelists successfully added") !== -1) {
                            $scope.IsColor = true;
                            $scope.Messages = response.data;                            
                            angular.element("#msg").focus()
                            return true;
                        }
                        else {
                            $scope.IsColor = false;
                            $scope.Messages = response.data;
                            angular.element("#msg").focus()                           
                            return false;
                        }
                    }, function (response) {
                        $scope.IsColor = false;
                        $scope.Messages = "Service unavailable. Please try again.";
                        angular.element("#msg").focus()
                        return false;
                    });
            } else {
                $scope.IsColor = false;
                alert('Please make sure to select a list of Panelists.');
                $scope.Messages = 'Please make sure to select a list of Panelists';
                angular.element("#msg").focus()
                return false;
            }
        }
        else {
            $scope.IsColor = false;
            alert('Please make sure to enter an ID');
            $scope.Messages = 'Please make sure to enter a Zoom Webinar ID';
            angular.element("#msg").focus()
            return false;
        }
    };

Answer №1

Not exactly providing an answer, but there seems to be no significant issue as evident in the example. (Except for the fact that $scope.Messages should always be an array instead of a string.)

I tested your function with a simulated http-request and it appears to be functioning correctly. You should verify the response being returned from the http-request.

angular.module('MyApp', []).controller('MyController', function($scope, $q){

        $scope.arr =[1,2,3];
        $scope.webinarId = '1234';
        $scope.IsColor = false;

function mock(isResolve){
  return $q(function(resolve, reject){
    setTimeout(function(){
    
      if(isResolve){
          resolve({data:['Panelists successfully added','message 1', 'message 2']});
       }else{
           reject({data: ['error 1', 'error 2']});
       }
    }, 1000);
  
  });
}

// Rest of the Angular controller code...
 
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>

  <div ng-app="MyApp" ng-controller="MyController">

                    <div>
                        <input type="button" value="Upload" id="btn-upload" ng-click="Upload()" />
                    </div>

                    @* Excel Contents Table *@
                    <table class="table mt-4 mb-5" id="tblPanelists" ng-show="IsVisible">
                        <tr>
                            <th>Name</th>
                            <th>Email</th>
                        </tr>
                        <tbody ng-repeat="p in Panelists">
                            <tr>
                                <td>{{p.Name}}</td>
                                <td><a href="mailto:{{p.Email}}">{{p.Email}}</a></td>
                            </tr>
                        </tbody>
                    </table>
                    <div id="msg" ng-repeat="msg in Messages" ng-style="IsColor && {'color':'green'} || {'color': 'red'}">{{msg}}</div>
                    <div class=" mt-3">
                        <button type="submit" class="btn btn-admin-blue" id="btn-add-panelists" ng-click="AddPanelists()"
                                ng-disabled="disableSubmit">
                            Submit
                        </button>
                    </div>
                </div>

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

"The issue with the nested nth-child property is that it only affects the first element it is applied to

Having trouble with the nth-child property. The issue lies with the #subnav element. I'm unsure why nth-child isn't working as expected (supposed to change border color and width). Here's the problem and code snippet : <div class=" ...

Tips for locating a particular row in Protractor

Can you explain how the solution discussed in this Stack Overflow thread works? I'm interested in understanding the specific logic behind selecting ID0001 in the code snippet provided below: element.all(by.repeater('item in $data track by $index ...

Error in Meteor: TypeError occurs when trying to use FS because it cannot read the property 'Collection' as it is undefined

Currently grappling with a challenge in my /server/main.js file while using Meteor 1.6 and AngularJS (Angular 1). Attempting an import as shown below: import { FS } from 'meteor/cfs:filesystem'; Although Meteor can resolve it without issue, the ...

AngularJS inputs using ng-model should be blank when in the pristine state

Check out this input element within an HTML form: <input ng-model="amount" /> Currently, the input displays as $scope.amount = 0 in the controller. I want to start with a blank input field instead. This way, users can easily input data without havi ...

Is there a way to include a button at the top of the Notiflix.Loading() overlay for closing or stopping it?

I've integrated the "notiflix" library into my project, and I'm currently using notiflix.loading.pulse() for a lengthy process. While this works perfectly fine, I would like to add a button (for closing/stopping the process) on top of the loading ...

Textfield with predictive text suggestions

I am currently working on implementing an autocomplete textfield for my Rails application, following the example from the Agile Web Development with Rails, 3rd Edition. However, when I try to insert their demo code: <%= stylesheet_link_tag &apo ...

Troubleshooting ng-view with partials in AngularJS/Express: What to do when it

Everything was working fine until I attempted to display a partial file in ng-view. /public/app/app.js angular.module('app', ['ngResource', 'ngRoute']); angular.module('app').config(function($routeProvider,$locati ...

Tips for turning off the full screen feature in Google’s web viewer

I have been using an embedded Google Viewer with iframe to display a PDF. I am trying to remove the full-screen popout feature from it and disable right-click within the iframe. I have tried several solutions but nothing seems to work. The URLs for my PDF ...

What is the best approach for handling errors in a NestJS service?

const movieData = await this.movieService.getOne(movie_id); if(!movieData){ throw new Error( JSON.stringify({ message:'Error: Movie not found', status:'404' }) ); } const rating = await this.ratingRepository.find( ...

I'm struggling to figure out where I went wrong with the Mongoose unique pre-save validation. What could

I am in the process of developing a User model that requires a unique username. Below is the code snippet for the model: var mongoose = require("mongoose"); var Schema = mongoose.Schema; var UserSchema = new Schema({ username: String, password: ...

Chrome Web Store issues an overly stringent warning for accessing a public API

A new Chrome Extension called FrontPage was recently created, utilizing the New York Times API. The extension sends an AJAX request to the API and receives a JSON response. However, to make this possible, specific permissions need to be set in the manifes ...

In IE, the hover state of the background color and sub menu is frequently toggling

I've been struggling with this issue all week. I have a CSS dropdown menu that uses both standard lists and content boxes as sub menus. The problem lies in IE, where each LI has an anchor tag that is set to display block in order to fill the parent LI ...

Notifying users with a jQuery or Javascript alert when they click the back

I am trying to create an alert or redirection for users when they press the back button, but so far, all the solutions I have attempted only trigger the alert after a form is submitted. Here is the current ineffective code I am using: $(function() { i ...

What is the best way to bind the value of total when working with forms and the bind method?

I am working on a form where I need to pass the value of total. Regarding the total: I have successfully passed the value of the cart, which is an array. const [total, setTotal] = useState<number | undefined>(undefined); const calculateTotal = () ...

Creating a semi-circular shaped rectangle using CSS

Is it possible to achieve the unique rectangle borders shown in the image using border-radius or any other CSS property? Here's what I'm trying to create: https://i.sstatic.net/YKPEW.png Currently, this is what I've been able to achieve us ...

Animating CSS when closing a modal box

I followed the instructions from a tutorial on W3Schools here to create this code. The "open model" button triggers the modal to open with a smooth CSS animation, which looks great. However, when I click the close button, the modal abruptly closes without ...

What is the best way to create a hover effect for Material Icons?

Having issues with Material Icon not displaying the specified changes when using CSS modules in my project import SettingsIcon from "@mui/icons-material/Settings"; import css from "./LandingPage.module.css"; <SettingsIcon className= ...

Enable a click event within an iFrame by clicking on an element in the parent document

I am attempting to trigger the click event of an element inside an iFrame (specifically a standard Twitter follow button) when clicking on an element within my main webpage. Below is the code snippet I have been experimenting with, but unfortunately it do ...

Troublesome Navigation Bar Dilemma: A Conundrum in HTML and CSS

Help needed with my homepage navigation bar that is acting up. The last button link seems to be extending further down than it should, and it's turning the text below it into a hyperlink as well. I'm not very experienced with programming, so any ...

Ways to detach event listener in Vue Component

One of my Vue2 components has a custom eventListener that I added in the mounted lifecycle hook. I am now trying to figure out the correct way to remove this listener when the component is destroyed. <template> <div> ... </di ...