Adjust the color of the button and update the text using AngularJS

i have been attempting repeatedly, but to no avail. Here is my button:

<div ng-class="User.active? 'btn btn-danger' : 'btn btn-success' "
     ng-click="User.active=!User.active">
    {{ User.active ? 'Desactive' : 'Active'}}
</div>

My goal is to link this button with the function for deactivating and activating a user.

public string Deactivate_User(AspNetUser User)
       {
        if (User == null) return "User Not Updated! Try Again";
        var userToUpdate = db.AspNetUsers.FirstOrDefault(x => x.Id == 
  User.Id);
        if (userToUpdate == null) return "User Not Found.";
        if (userToUpdate.IsActive == true)
        {
            userToUpdate.IsActive = false;

        db.SaveChanges();
        return "User successfully deactivated.";
    }

        return "User already deactivated.";
    }

If the button is green, then the function should be like this:

public string Activate_User(AspNetUser User)
    {
        if (User == null) return "User Not Updated! Try Again";
        var userToUpdate = db.AspNetUsers.FirstOrDefault(x => x.Id == 
        User.Id);
        if (userToUpdate == null) return "User Not Found.";
        if (userToUpdate.IsActive == false)
        {
            userToUpdate.IsActive = true;

            db.SaveChanges();
            return "User successfully activated.";
        }

        return "User already activated.";
    }

To elaborate on my issue further: images : view image description here

Answer №1

From my perspective, I prefer using anchor tags over input type="button". With anchor tags, you have more flexibility to style and customize as needed, especially since both the anchor tag and ng-click serve a similar purpose of triggering actions on click.

It can be assumed that your user objects contain a property indicating their active or inactive status.

To define your class, consider replacing it with

ng-class="{btn: true; btn-danger: !User.active; btn-success: User.active}"

This setup will result in classes "btn btn-danger" when User.active is false, and "btn btn-success" when User.active is true, adjusting dynamically with changes to the user's status. Assuming that btn-danger displays red and you have bootstrap css, btn-success would display green. If not, adjust your own css accordingly.

In the .then section after your http post, analyze the response to ensure a successful activation of your user backend with a status code of 200 before setting User.active=true. It is crucial to confirm the need for updating your user object based on the response. In case of an error, utilize the .then function to communicate an appropriate error message to the user.

To modify the text on the button, angular can also handle that task efficiently. Include

{{User.active?'Deactivate':'Activate'}}
within the anchor tag text.

<a ng-class="{btn: true; btn-danger: !User.active; btn-success: User.active}"
   ng-click="DesactivateUser(User)">\ 
 {{User.active?'Deactivate':'Activate'}}
</a>

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

Node server encountering issue with undefined data in POST request

I have been working on an Angular2/Node.js application. Everything seems to be working fine when I retrieve an object from the Node server, but I'm facing an issue when trying to post data to the server. The request.body always shows as undefined. Can ...

locating the image file path in an Angular ng file upload

Once I've uploaded an image using ng-file-upload to a server like https://angular-file-upload-cors-srv.appspot.com/upload, all I receive in response is the image name. Now, in order to display the image in HTML, how can I achieve this? <img ng-sh ...

In mvc.net 4, Ajax is only compatible with the httpGet method and not with httpPost

There are two methods, httpGet and httpPost, inside the Login action. Currently, when an ajax call is made, it only works with the httpGet method of Login. I would like it to work with the httpPost method of Login. Thank you in advance for your answer! ...

Transform your website by swapping out the traditional front page and menus for a dynamic module

Exploring the world of Drupal, I recently created a module in Angular that displays ads and articles from a JSON file. When I visit localhost/drupalTest/ads, I can see all the ads displayed in my desired format. Now, I am curious if it is possible to repla ...

Oops! An error occurred while trying to load the myApp module. The module 'ui.bootstrap' is missing and causing the failure

When using Firefox, I encountered the following error: SyntaxError: syntax error xml2json.js:1 SyntaxError: syntax error ui-bootstrap-tpls-0.13.0.js:1 Error: [$injector:modulerr] Failed to instantiate module myApp due to: [$injector:modulerr] Failed to in ...

The decision will be dependent on the outcomes provided by the $resource promise

I have been working on calling my API with AngularJS to retrieve a list of 'reports' and then displaying them in a modal or saving the sale depending on whether any results were returned. I've been struggling with this for a while and would ...

Transmit a cookie from the front-end to the back-end using Angular in HTTP requests

I am currently in the process of developing a web application using AngularJS. This application consists of: a frontend component that solely retrieves data from a backend through multiple queries; a backend with various RESTful services, each returning ...

Include features once JSON has been loaded

Received this JSON data: { "info": [ { "id": 999, "products": [ { "id": 1, }, { "id": 2, } ] } ] } Info -- products -----id Here is the factory code snippet: AppAngular.factory('model', ['$http', f ...

Combining Rails API with AngularJS and IonicFramework

I'm embarking on a new project and feeling unsure about my chosen setup/approach. The project involves creating a list directory that doesn't require high computing power. My initial plan is to develop a website using Rails Api and AngularJs (al ...

There seems to be an issue with accessing the Angular module, even though it has been clearly

While attempting to execute the code below, two errors are encountered: Error: [$injector:nomod] Module 'rooms' is not available! The module name is spelled correctly and loaded dependencies have been included. The modules are structured in the c ...

How to Filter Fields in AngularJS Based on a Start Date and End Date?

Hey everyone, I'm trying to filter items based on the start and end dates using the daterange functionality in my meanjs app. I've tried multiple approaches but haven't found a solution yet. If anyone knows how to do this, please help me out ...

Dynamic Searching in ASP.NET Core MVC Select Component

I need assistance with implementing a dynamic search feature on my Login page. Here's the scenario: When a user enters a username, let's say "Jh" for Jhon, I want to display a select list next to the login form that lists all the usernames from t ...

Challenge encountered while attempting to implement grid system in ionic framework

I'm completely new to the world of ionic framework, and I really need some assistance in completing this view. Please see the image reference https://i.stack.imgur.com/WOBFw.png I have made an attempt at it with the following code: <div class ...

Testing infinite scrolling with the help of protractor

It seems like the infinite scrolling feature in ng-grid is not exactly infinite, but it's the closest comparison I could come up with for what I am observing. In our application, we are using ng-grid to display data in a table with approximately 170 ...

MVC2: The Search for HtmlEncode

When working on my code, I encountered the challenge of needing to return a Json string without being able to use HtmlEncode in MVC2. How can I encode a string to eliminate illegal characters for JSON formatting? ...

What is the best way to combine two arrays of objects in AngularJS?

How can I merge the existing object array with another one in AngularJS to implement the "load more" feature? Specifically, I want to add the AJAX response to the existing data each time. Currently, I have a variable called $scope.actions that holds the ...

Comparison between UI Router and ngRoute for building single page applications

Embarking on a new Angular project, a single page app with anticipated complex views such as dialogs, wizards, popups, and loaders. The specific requirements are yet to be clarified. Should I embrace ui.router from the start? Or begin with ngRoute and tra ...

External function's access to scope

Having an issue with the external function OnLoginFail when calling the function showFormAndHideMessage from it. I attempted to use: angular.element($("login")).scope().showFormAndHideMessage().$digest(); however, this approach did not yield any results ...

Capturing a web request in C# by converting it into JSON and then serializing it into a C

Currently, I am attempting to communicate with a restful API and retrieve the response using a c# object. In the past, I have successfully captured responses using WebRequest and Get methods. However, when trying to use Post and Streamreader, I suspect th ...

Is it possible to circumvent the use of ng-repeat in any manner?

When displaying JSON data in an Ionic view using multiple ng-repeats, the console log shows that the data is retrieved quickly. However, it seems that having multiple ng-repeats is causing a slowdown in performance, resulting in the app freezing and taking ...