Using AngularJS to dynamically apply a CSS class to message text depending on the HTTP post response

I am looking to implement a method for adding a CSS class to the text color of a message based on the response.

Currently, I achieve this by:

if (response.data.status == 201) {
    angular.element(document.getElementById("msg")).addClass("text-green");
    $scope.msg = 'Users created for Meeting ' + r.id
        + ' on ' + $filter('date')(r.updated_at, 'M/d/yyyy')
        + ' at ' + $filter('date')(r.updated_at, 'HH:mm:ss');
    console.log("Status Code= " + response.data.status + ", Status Text= " + response.data.message);
    return true;
}
else {
    angular.element(document.getElementById("msg")).addClass("text-red");
    $scope.msg = r.message;
    angular.element("#meeting-id").focus()
    console.log("Status Code= " + response.data.status + ", Status Text= " + response.data.message);
    
    return false;
}                        

Although it is effective, I now have two classes that can be applied to success and error messages. I am seeking guidance on how to add these classes in order to remove the inline style attribute that changes the text color to red or green.

The class names are:

•   Success: “text-green”

•   Error: “text-red”

What would be the right approach to accomplish this?

Any assistance is highly appreciated.

Thank you, Erasmo

Answer №1

If you want to apply different styles dynamically, you can utilize ng-class in your JavaScript file.

      $scope.responseCode = response.data.status;

Then, in your HTML:

    <div ng-class="{'text-success':responseCode == 201,'text-danger':responseCode != 201}">
        <h1>Welcome Home!</h1>
        <p>I like it!</p>
    </div>

To learn more about ng-class, visit: https://docs.angularjs.org/api/ng/directive/ngClass

Alternatively, you can also use classList.add:

For a success message, you can do:

     angular.element(document.getElementById("msg")).classList.add('green');

For an error message, you can do:

angular.element(document.getElementById("msg")).classList.add('red');

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

What is the best way to ensure that JavaScript code is executed in a specific sequence?

Even though I understand that Javascript is not the same as C# or PHP, I keep encountering an issue with Javascript - specifically with how I use it. Here's the scenario: function updateStatuses(){ showLoader() //displays 'loader.gif' on ...

Integrating photospheres into your Squarespace website design

Attempting to incorporate photospheres into my Squarespace website has been a challenge. The Google Maps option is functional, but it doesn't meet my specific requirements and appears like this: <iframe src="https://www.google.com/maps/embed?pb=! ...

Using Jquery to select a specific id for an input element that is a checkbox

I've been working on a snippet of jQuery code that I'd like to tailor to be more specific for one of two different input elements on my HTML page. <script> // ensure only one box is checked at a time $(document).ready(function() { ...

Mastering Array Dispatch in VueJS

I've encountered an issue while trying to send an array of data to the backend. I attempted to include [] in the dispatch variables and on the backend, but it only captures the last data sent to the backend. My objective is to associate each data with ...

Guide for locating and tallying occurrences of a 4-digit number within an array of objects using MongoDB, such as lottery numbers

I am in the process of developing a lottery game where users can enter a 4-digit number between 1-9 (e.g. "1, 4, 5, 8"). The game will then generate a random winning 4-digit number using Math.random. My objective is to calculate the number of matches for ...

Objects shifting position as the browser window is resized or zoomed

I've scoured through numerous examples, but none seem to work for my specific situation. On my webpage, I have multiple tables nested within a <div>, which serves as a background element (as it doesn't cover the entire screen). However, whe ...

Navigating through angularjs is as simple as following these steps

My main directory folder is named angularjs and contains the following files: 1.index.html 2.main.html 3.blue.html 4.red.html 5.green.html I am trying to set up routing using AngularJs, but I am encountering an error. Can you help me figure out what I am ...

Displaying a loading progress bar while the website is being loaded using Javascript

Currently working on developing a GUI site, I am looking to implement a progress bar. However, I require some JavaScript code that can detect the loading status of the site along with the number of elements/images that have been loaded so far, as well as d ...

How can I activate div elements by clicking on a specific div using Angular 2?

I have created a custom component with search dropdown functionality for selecting dates. <div class="search-dropdown calender-dropdown "> <div class="search-dropdown-tabs-wrp"> <ul class="search-dropdown-tabs"> <li& ...

Tips for hiding the calendar icon once a form has been submitted

Below is the HTML code snippet for the date field. <asp:TextBox ID="txtExpiryDate" runat="server" Width="80px" MaxLength="10" CssClass="fromDate" /> And here is the HTML code snippet for the Submit button. <asp:Button ID="cmdSubmit" runat=" ...

Move object smoothly off screen without any delay

I have been experimenting with Animate.CSS and basic Jquery to add animations to elements coming on and off the screen. However, a problem I have encountered is that there is noticeable lag, especially when there is a background slideshow running simultane ...

Is there a way to modify an element in an array in AngularJS without using splice?

I encountered a situation similar to the one described in this post here, where I not only want to retrieve an element but also change its name value. I came across a method that involves using splice: dataList.splice(index, 1); dataList.splice(index, 0, ...

What is the correct way to access an element with spaces in handlebars while working with node.js?

I have an object containing values with spaces in strings. For example: object = { "group of people": [ { (...) } ], "another group of people": [ { (...) } ] } Now, I want to use this object with the handlebars helper block in my view ( ...

Make sure to update the package.json file at multiple locations following the execution of the "npm i" command

My goal is to automatically detect any newly installed packages based on my package.json file. This way, whenever I run "npm i", the new package will be added not only to the usual "dependencies" section but also to a custom section called "extDependenci ...

Collecting all Material-UI components into a single document

Currently, I am engaged in a Meteor project that utilizes Material UI and ReactJS. I wish to streamline the process by creating a single file that imports all necessary Material UI components for my project. This way, instead of adding individual exports ...

Deselect all checkboxes other than the daily selection

I recently designed an E-commerce website that includes a package customization feature where users can modify their packages. The initial question presents three radio button options: 1. Daily 2. Weekly 3. Monthly If the user selects 'daily&apos ...

Angular-Phonegap - The issue with "min-height: 100%" not functioning properly

I am faced with this specific HTML file: <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="format-detection" content="telephone=no" /> <!-- NOTE: Make sure to remove the width=d ...

Troubleshooting the issue of React forms hook not functioning properly with Material UI Select input

How the Textfield below should load: https://i.sstatic.net/29Sz4.png How it actually loads: https://i.sstatic.net/TdPYM.png My Select component, created using Material UI and React form hook, is not loading the default value as expected. The component ...

What methods can a Discord Bot use to respond with specific messages to individual users?

Hey there! I'm dipping my toes into the world of coding and thought it would be fun to create a Discord bot that gives different responses each time it's mentioned. Just so you know, I'm working with Discord.js version 13 for this project. ...

Iterating over an array of numbers in AngularJS

I have an array of numbers $scope.N = [1,2,3,4]. I want to loop through this array in my HTML code using ng-repeat, similar to the example with JSON ng-repeat. <div ng-repeat="num in N"> {{num}} </div> How can I achieve this with a ...