How can you switch a CSS class on a clicked element using AngularJS?

Is there a way to toggle a class on click in AngularJS using predefined directives without writing JavaScript code?

I attempted to achieve this by using ng-class:

<button ng-model="toggle" ng-class="{'red' : toggle}">Change Class</button>

Check out the demo on CodePen

Answer №1

Implement a switch using the ternary operator in the following way:

<button ng-model="toggle" ng-class="toggle ? 'red' : ''" ng-click="toggle=!toggle">Change Class</button>
  1. ng-click="toggle=!toggle": Clicking on the button will toggle the value of toggle.
  2. The ternary operation in ng-class will add the class red if toggle is true, and remove it if false.

Example:

.red {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
  <button ng-model="toggle" ng-class="toggle ? 'red' : ''" ng-click="toggle=!toggle">Change Class</button>
</div>


You can also achieve the same functionality with:

<button ng-model="toggle" ng-class="{'red' : toggle}" ng-click="toggle=!toggle">Change Class</button>

.red {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
  <button ng-model="toggle" ng-class="{'red': toggle}" ng-click="toggle=!toggle">Change Class</button>
</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

Adjust the svg rate using jQuery or JavaScript

Seeking help with a gauge I found on CodePen - struggling to adjust bubble values... <path id="Fill-13" fill="#F8B50F" d="M3.7 88.532h26.535v-#.795H3.7z"/> Can change the bars in JS, but not the bubbles using jq/js. Adjust the gauge with values be ...

Add a trash can or delete icon within every row of a table using Vue.js

I am new to vue.js and I'm struggling to implement a trash icon in each row of a table for deleting rows. Additionally, I'm trying to make the input of a cell act as a dropdown menu or list within the table rows. I recently came across this scrip ...

Error: The function semrush.backlinks_refdomains does not exist as a valid function

Hey there! So I've been working with the SEMRUSH API and encountered an issue when trying to retrieve data using backlinks_refdomains and backlinks_refips. However, when I called the domain_rank function, it responded in JSON format without any proble ...

Efficiently managing modules with requirejs and Backbone.Marionette

After organizing the file structure of my web app, utilizing RequireJs and Backbone.Marionette, it now looks like this: |- main.js |- app.js |- /subapp1 |- subapp1.js |- subapp1.router.js |- /subapp2 |- subapp2.js | ...

Experiencing difficulties with node and asynchronous programming

I'm attempting to use async-waterfall in order to fetch data from an API, save it as JSON, and then store it in a database. Here is a snippet of the code I have so far. Can someone assist me with this process? async.waterfall([ function getBo ...

Update class name in React component based on state change

My current setup involves the setting of active and class flags as shown below: constructor(props) { super(props); this.state = {'active': false, 'class': 'album'}; } handleClick(id) { if(this.state.active){ this.s ...

ngSelected is not affecting the value of ngModel in AngularJS

Below is a select list with an ngSelected attribute that correctly selects the value in the expression, but the model for the select does not update accordingly. Even though I can select the "High" Value and trigger the ngSelected, the display shows an emp ...

When embedding HTML inside an Angular 2 component, it does not render properly

Currently, I am utilizing a service to dynamically alter the content within my header based on the specific page being visited. However, I have encountered an issue where any HTML code placed within my component does not render in the browser as expected ( ...

In what situations is it essential to utilize the `rerender` function in the React Testing Library?

In the past, my team and I usually focused on writing React Testing Library (RTL) tests for the main parent components that contained numerous nested child components. This approach made sense and proved to be effective. The child components in question we ...

Activate and deactivate button

I've tried multiple examples on this site for enabling and disabling a button using javascript with jquery, but none of them seem to work for me. Here is my current dilemma: <asp:TextBox ID="mytext" runat="server" onkeyup="enableButton(this, 3)"/ ...

What causes the "Cannot read properties of undefined" error in Vue when an array is initialized and output is still being displayed?

I am working with two vue files, namely App.vue and a component called UsersPage.vue. UsersPage.vue: <script> export default { data:() =>({ usersList : [] }), methods:{ async createUsersList(){ this.usersLi ...

Changing array indices in JavaScript by splicing elements

I'm experiencing a curious issue that seems to involve overwriting array indices after splicing, or at least that's what I suspect. This problem arises in a small game project built using phaser 2 - essentially, it's a multiplayer jumping ga ...

Different ways to automatically trigger a function in JavaScript

There are various ways to trigger a function automatically in javascript when a page loads. I am interested in knowing which method is considered the most effective and reliable. If you have a unique approach that differs from others, please share it here ...

Create a loop in Vue.js 3 without the need for a query

Can someone help me understand how to fetch data using a loop in Vue.js version 3 when working with queries? I am trying to retrieve an object based on its id, which is obtained from the URL. However, I seem to be facing some difficulties. Any guidance wou ...

What is the best way to transfer information between two views in Aurelia?

I have two different perspectives, one called logo and the other called folder. The logo view should display something from the folder view if the folder is empty. logo.html <template> <require from="company-assets/folders"></require> ...

Is it possible to utilize both href and ng-click in Angular.js?

Here is a text box: <input type="text" ng-model="SearchText" > And also, a link: <a href="#logout" ng-click="SearchText=''">Logout</a> I am trying to make both actions work in the above hyperlink. The ng-click should clear t ...

Error arises when using ODBC PDO alongside Ajax functionality

I've encountered a problem while working on a project at my job. I'm using PDO queries and ajax to generate dynamic elements, but I can't seem to fix a specific issue. The problem is that regardless of the option selected in two dynamically ...

Unlocking the power of Google Feed API to incorporate MIXED FORMAT in AngularJS

Currently, I am utilizing Google's Feed API in conjunction with AngularJS to retrieve my feed data in a mixed format of both JSON and XML. Although I have attempted to modify the method and callback tags to MIXED_FORMAT as per Google's documentat ...

Keep the music playing by turning the page and using Amplitude.js to continue the song

I have implemented Amplitude.js to play dynamic songs using a server-side php script. My objective is to determine if a song is currently playing, and if so, before navigating away from the page, save the song's index and current position (in percenta ...

How come the parameters in my function are being displayed as boolean values in JSDocs when that is not the intended behavior?

I am documenting my journey of following the React tutorial for tic-tac-toe, and I'm puzzled as to why the parameters of my function are showing up as boolean values in JSDocs when they are not supposed to. When I hover over the function with my curs ...