Switching CSS styles with ng-click

Is there a way to toggle a CSS style based on an ng-click event?

When the user clicks the ng-click element for the first time, the style is applied. However, when they click the ng-click element for the second time, the CSS does not change as expected to toggle.

See the code snippet below for a working example:

HTML:

<h1 ng-style="myObj" ng-click="change()">Welcome</h1>

JavaScript:

app.controller("myCtrl", function ($scope) {
    $scope.myObj = {
        "color": "white"
    }
    $scope.change = function () {
        $scope.myObj = {
            "color": "red"
        }
    }
});

Is there a way to toggle CSS class based on an ng-click event?

If anyone can guide me on how to achieve the same, it would be greatly appreciated.

Answer №1

Utilize the ng-class directive along with a toggleable flag.

/* Set default class properties */
h1 {
  color: blue;
}
.red {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<h1 ng-app ng-class="{'red': flag}" ng-click="flag=!flag">Welcome</h1>

The initial value of flag is undefined, making it falsey and preventing the class from being applied. Upon clicking, flag = !flag will switch the flag to true, triggering the addition of the red class. Subsequent clicks will toggle the flag to false, removing the red class.

Answer №2

Give this a shot.

var app = angular.module('myApp', []);
app.controller("myCtrl", function($scope) {
  $scope.myObj = {
    "color" : "blue"}
$scope.change=function()
{
  $scope.myObj.color == 'red' ? $scope.myObj.color = 'blue' : $scope.myObj.color = 'red';
 
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl"><h1 ng-style="myObj" ng-click="change()">Welcome</h1>
</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

Customizing the appearance of the Bootstrap Typeahead

I've been experimenting with the Bootstrap Typeahead for my search feature. I successfully implemented the dropdown list using Ajax. However, I am looking to customize the width, padding, and background color of the dropdown menu, which is currently w ...

Transforming data structures into arrays using Javascript

Could someone help me with converting the following code snippet? const words = {told: 64, mistake: 11, thought: 16, bad: 17} I need it to be transformed into: const words = [ {text: 'told', value: ...

What is the proper way to structure the DATETIME format when making an API request to mySQL?

Frontend code: import React, { Component, useState, useEffect } from "react"; import Navbar from "../Navbar/Navbar.js"; import BarChart from "../BarChart/BarChart"; ... Backend code: //set up express server const express = require("express"); const app ...

"Trouble with props: List items not showing up after refreshing the page

I am facing an issue with my "Event Selector" component where it is not displaying the list items as expected. The component is supposed to create a button for each item in the 'lists' passed via props. Strangely, the items do not show up upon re ...

What drawbacks should be considered when utilizing meteor.js for development?

After viewing the meteor.js screencast, I was truly impressed by its seamless web application development capabilities, especially in terms of live updates and database synchronization. However, I am curious about its scalability once the website goes live ...

Tips for inserting a hyperlink into a Chakra UI toast

Exploring the integration of Chakra UI within my Next.js project has led me to a curious question: Can Chakra UI toasts accommodate links and styled text? If so, what is the process for implementing these features? ...

Implementing expiration dates or future dates with jQuery

How can I modify this jQuery code to display an expiration date specified in months or years? For instance, I have created a Membership Card for a client that is valid for 2 years, and I would like to include an expiration date in the script. Thank you j ...

Issue with IntelliJ: TypeScript Reference Paths Are Not Relative

I am currently using IntelliJ as my IDE, but I am facing an issue with configuring gulp-typescript to compile my typescript code. The problem arises from the fact that IntelliJ does not treat my reference paths relatively, instead it references them from m ...

What is the best way to choose multiple rows in a UI grid without the need to press and hold the CTRL key in

When working with a table in Angular, I encountered an issue where I couldn't select multiple rows by clicking. Unlike the table example provided below, my table at work only allowed for selecting one row at a time, making looping ineffective. My ques ...

Tips for automatically expanding all nodes with children when the page loads in the Wix Angular tree control

Is there a way to automatically expand all nodes with children when the page loads in an Angular tree control? The tree control is full of useful features, but this specific functionality seems to be missing. It does have a property for expanded nodes. Do ...

Comparing two datetime objects with time zone offsets in JavaScript: How to determine if one is greater than or less than the other?

So I'm faced with a situation where I need to compare two dates where the first date is 05.01.2008 6:00 +5:00 and the second date is 05.01.2008 7:00 +5:00 I'm struggling to find a way to convert these datetimeoffsets into a specific forma ...

Angular UI-Select's issue with duplicating tags while adding objects for tagging functionality

I have implemented the ui-select library to enable the "Tagging" feature in my project. Currently, I am utilizing an Array of objects where each object contains an id and a name. The functionality is working as expected. However, when a user types in a n ...

What is the reasoning behind excluding any JavaScript code between the <script> tags when our intention is solely to incorporate an external JS file?

It's puzzling to me why the author of the "Javascript & Jquery: the missing manual , second edition" recommends the following sentence: When including the src attribute to connect to an external JavaScript file, avoid placing any JavaScript cod ...

Retrieve Static Property Values Using jQuery/JavaScript in Backend Code

My challenge is to fetch the Max value and Percent value into a jQuery function. I attempted to retrieve these values using hidden variables and Session variables on page load, but they always return 0. Here are the properties: public static int Max { ...

What can I do to resolve the issue of my Navigation Bar being blocked by a Javascript map?

My navbar creates a dropdown menu when I hover over it, but the map generated with the script tag blocks it. Here is the current setup: // JavaScript Document //This will make the navigation bar responsive. function myFunction() { var x = document.ge ...

When trying to insert a string variable using Node and mysql, the operation fails

My attempt to add a string variable into the database is causing an issue. The boolean and integer values insert without any problems, but I keep receiving the following error message: Error: column "spike" does not exist (The value "spike" corresponds ...

Don't display the title if there is no query made in Angular

At the moment, my current setup looks like this: <title ng-bind-template="FuturePhones: {{query}}">FuturePhones</title> However, this results in the title displaying as follows when the page loads: FuturePhones: When I query my controlle ...

What could be causing my Angular code to submit back unexpectedly?

My goal is to make an initial call to the database to populate some dropdowns, after which all actions are done through AJAX. However, whenever I click a button on the page, it seems to be posting back and calling the function that fetches dropdown values ...

Is there a specific directive in Angular that allows for variable declarations using the "

This interesting piece discusses the usage of a let-name directive in the template: <ng-template #testTemplate let-name> <div>User {{ name }} </div> </ng-template> Can anyone tell me if this is a part of the standard ang ...

Divergence between Angular HTTP get response and network tab display

I've been encountering an intermittent issue where, when I use the Angular HTTP service to make a call, some values are coming back as undefined every 10th time or so when I refresh the page. It's strange because the network tab confirms that all ...