What is the best way to apply a class to a button in Angular when clicking on

Creating a simple directive with two buttons. Able to detect click events on the buttons, but now looking to add a custom class upon clicking.

There is a predefined class:

.red {
  background-color: red;
}

The goal is to dynamically apply this class when a button is clicked.

  • Initially, the login button will have the red class. Upon clicking the logout button, the red class should transfer to the logout button and be removed from the login button.

If the login button is clicked again, the class should switch back to the login button from the logout button.

Below is the implementation:

angular.module('app', ['ui.router']).directive('tm', function() {
  return {
    restrict: 'E',
    templateUrl: 'login.html',
    scope: {
      login: "&",
      logout: '&'
    },
    controller: 'f',
    controllerAs: 'vm'
  };
})

You can view the full code at the following link: http://plnkr.co/edit/Q1e8u0okOa4looLcb2YO?p=preview

Answer №1

Include a link function in your code block.

Here is an example:

link: function(scope, elm, attr) {
  elm.find("button").on("click", function(e) {
    elm.find("button").removeClass("red");
    angular.element(this).addClass("red");
  })
}

Check out the PLNKR for more information

You can also achieve the same effect using ngClass

Here is how you can do it:

JS

vm.isLogin = true;
vm.login = function() {
  vm.isLogin = true;
}

vm.logout = function() {
  vm.isLogin = false;
}

HTML

<button type="button" class="btn btn-default" ng-class="{'red': vm.isLogin }" ng-click='vm.login()'>Login</button>
<button type="button" class="btn btn-default" ng-class="{'red': !vm.isLogin }" ng-click='vm.logout()'>Logout</button>

See the updated PLNKR version here

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 process for invoking a function in ng-repeat after an object has been altered?

I am facing an issue with the following code snippet: <ul class="list-group" ng-init="curMarks=getTaskVotesModalInfo(task)"> <li ng-repeat="info in curMarks" class="list-group-item"> <span>{{info.worker}}</span> <span ...

Unable to process form submission using Ajax in ASP.NET MVC

I'm having trouble with submitting a form using ajax and opening a modal dialog after the ajax function is successful. Whenever I click the submit button, the process doesn't complete. Where could the issue be, in the ajax method or somewhere el ...

Executing an AJAX POST request from one domain (localhost:9393) to another domain (localhost:9696) using Spring Rest

I am encountering an issue with a form on one app running on localhost:9393. The JavaScript function used to post data is: function registerClient() { var postData = $("#client-reg").serializeArray(); var formURL = "http://localhost:9393/mPaws/client/re ...

Using Thymeleaf within Javascript code to generate a URL?

Here is my question: The project's base URL is : The test page URL is :, and on this page, I have included a JavaScript file called datatable.packer.js using the following code: <script type="text/javascript" th:src="@{/resources/js/datatable ...

AngularJS view fails to reflect updates in the model

This issue with Angular has been widely discussed online, but I ask for your patience. I have tried various solutions without success. Here is a simplified version of my code: View: <div ng-hide="{{beHidden}}"></div> Controller: // Set beHi ...

What is the best way to toggle the visibility of my menu using JavaScript?

I recently implemented a script to modify a CSS property in my nav bar as I scroll down, triggering the change after reaching 100px. $(window).scroll(function() { var scroll = $(window).scrollTop(); //console.log(scroll); if ...

What are the circumstances under which JavaScript GCP libraries return null values?

My current project involves working with GCP and Firebase using typescript. I have been utilizing the provided libraries, specifically version 8 of Firebase, and have encountered some unexpected behavior. For instance (firebase, ver. 8.10.1) import 'f ...

Promise disregards the window being open

I'm facing an issue with redirecting users to Twitter using window.open in a specific function. It seems like the instruction is being ignored, even though it works perfectly on other pages. Any ideas on how to fix this? answerQuestion() { if ...

Both the client and server sides are in sync with the latest data, yet the rendering fails to display the recent updates

The technologies I am currently utilizing include Nodejs, Express, MySQL, and EJS. My current task involves: Creating an app.get function that retrieves necessary data (posts) from MySQL, then renders a file using that data app.get("/" + element.name, f ...

AngularJS is experiencing issues with its routing functionality

Currently, I am delving into the intricacies of angular js routing concepts as part of my learning journey. To explore this further, I have set up an inner folder within the app containing two sample test html pages. However, upon running the app, it fail ...

iOS CORS ajax request is stuck at state 0 during processing

I am facing an issue with making a CORS login AJAX call from my iPhone using $.ajax. The request fails and reaches the fail callback, showing the jqXHR object state as: { readyState: 0, status: 0, statusText: "error" } Strangely, on my PC the request ...

Modifying multiple objects with Vue's V-Model

When utilizing the mounted function in Vue to assign two different objects in the data area and bind one of them to a form, an unusual issue arises: Both objects change when input values are entered in the form For example: <template> <v-card ...

I'm struggling to understand how to interpret this. The v-tab function seems to be generating a button with various properties, but I'm unsure which specific property is related to

The V-tab below generates the button known as the right one on the v-app-bar: https://i.stack.imgur.com/DzNmq.png <v-tab :to="'/demo'" active-class="text--primary" class=&quo ...

What steps are involved in developing a jQuery Validator function to enforce username restrictions?

Currently, I have implemented a method to enforce strong passwords like this: $.validator.addMethod('goodPassword', function(value, element){ return this.optional(element) || value.length >= 6 && /\d/.test(val ...

How can an array be concatenated using tabs?

I am currently in the process of integrating with an old system that requires a value to be sent via a GET request as a tab delimited string. I have my data stored in an array, but I am facing difficulty when attempting to properly format it using the join ...

Adjusting the page size in the material table to display all items

I am currently working with React and Material Table. Objective My goal is to provide the user with the option to set the pageSize to 'All' in order to display all rows in the material table. Steps Taken I utilized the useState hook to create ...

Utilize Angular 2 to search and filter information within a component by inputting a search term from another component

In my application, I have a Component named task-board which contains a table as shown below: <tr *ngFor="let task of tasks | taskFilter: searchText" > <td>{{ task.taskName }}</td> <td>{{ task.location }}</td> <td>{{ ta ...

Search a location database using the user's current coordinates

Currently, I am working on a project that involves a database containing locations specified by longitude and latitude. Upon loading the index page, my goal is to fetch the user's location and then identify every point within a certain distance radius ...

Counting the number of AngularJs elements in a table

<table align="center"> <tr> <th>No</th> <th>Movie Title</th> </tr> <tr data-ng-repeat="mov in movie | pagination: curPage * pageSize | limitTo: pageSize | filter:searchText" data- ...

Straightforward JSON issue

I am new to JSON and I need to work with it now. I have tried several examples from the jQuery page, but they don't seem to be working for me. I have a *.php file that generates a string. From what I understand, this is how I pass JSON data from PHP ...