Implementing class toggling in AngularJS with ng-class

Trying to change the class of an element with ng-class

<button class="btn">
  <i ng-class="{(isAutoScroll()) ? 'icon-autoscroll' : 'icon-autoscroll-disabled'}"></i>
</button>

isAutoScroll():

$scope.isAutoScroll = function()
{
    $scope.autoScroll = ($scope.autoScroll) ? false : true;
    return $scope.autoScroll;
}

If $scope.autoScroll is true, apply icon-autoscroll through ng-class. If false, use icon-autoscroll-disabled

The current method results in this error:

Error: Lexer Error: Unexpected next character  at columns 18-18 [?] in expression [{(isAutoScroll()) ? 'icon-autoscroll' : 'icon-autoscroll-disabled'}].

How can this be corrected?

UPDATE

Solution 1 (obsolete):

<button class="btn" ng-click="autoScroll = !autoScroll">
  <i ng-class="{'icon-autoscroll': autoScroll, 'icon-autoscroll-disabled': !autoScroll}"></i>
</button>

UPDATE 2

Solution 2:

I advocate for using Will's proposed Solution 3 due to its simplicity and clarity when it comes to ternary operators. Here's how it looks:

<button class="btn" ng-click="autoScroll = !autoScroll">
  <i ng-class="autoScroll ? 'icon-autoscroll' : 'icon-autoscroll-disabled'"></i>
</button>

This translates to:

If autoScroll == true, //apply class 'icon-autoscroll', else //use 'icon-autoscroll-disabled'

Answer №1

Guide on utilizing conditionals in ng-class:

Method 1:

<i ng-class="{'icon-autoscroll': autoScroll, 'icon-autoscroll-disabled': !autoScroll}"></i>

Method 2:

<i ng-class="{true: 'icon-autoscroll', false: 'icon-autoscroll-disabled'}[autoScroll]"></i>

Method 3 (angular v.1.1.4+ added support for ternary operator):

<i ng-class="autoScroll ? 'icon-autoscroll' : 'icon-autoscroll-disabled'"></i>

Plunker

Answer №2

To offer a different approach, using the javascript logic operator '&&' which returns the last evaluation, you can achieve the same result through this method:

<i ng-class="autoScroll && 'icon-autoscroll' || !autoScroll && 'icon-autoscroll-disabled'"></i>

This syntax is only slightly more concise but personally, I find it easier to understand.

Answer №3

To add multiple classes based on a condition:

<div ng-click="OpenPopup(s)" 
ng-class="{'class1 class2 class3':!isNew, 
           'class1 class4': isNew}">{{ isNew }}</div>

When isNew=false, apply classes: class1 + class2 + class3.

When isNew=true, apply classes: class1 + class4.

Answer №4

<div data-ng-init="toggleFeature=false" 
     data-ng-click="toggleFeature=!toggleFeature" 
     data-ng-class="{'activated': toggleFeature}">
    Click here to switch my style!
</div>

Similar to the functionality of jQuery's toggleClass method, this code allows you to alternate the appearance of the element by toggling the 'activated' class on and off with a click.

Answer №5

autoscroll is a variable that will be defined and updated in the controller:

<span ng-class= "autoscroll?'class_if_true':'class_if_false'"></span>

To apply multiple classes depending on a condition, you can use the following syntax:

<span ng-class= "autoscroll?'first second third':'classes_if_false'"></span>

Answer №6

This is how I achieved the desired outcome:

<button class="btn" ng-click='toggleClass($event)'>Click me for button one</button>
<button class="btn" ng-click='toggleClass($event)'>Click me for button two</button>

Within your controller:

$scope.toggleClass = function (event) {
    $(event.target).toggleClass('active');
}

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 strategies can I employ to address this historical issue?

Encountered TypeError: (0 , history_history__WEBPACK_IMPORTED_MODULE_6_.default) is not a function This issue arises in my history.js file import { createBrowserHistory } from 'history'; export default createBrowserHistory({ forceRefresh: tr ...

Click on the child element while it is already being clicked by manually implementing the 'declick' function in Javascript

Hey there, I'm looking for suggestions on a better title for this issue. I couldn't come up with the right wording myself. Problem I currently have a Google Maps element with pointer events set to none, preventing it from being scrolled when ho ...

Changing the `$location.path` updates the URL without triggering a redirect

When I try to redirect to another page by clicking a button or a link, the URL changes but the redirection doesn't happen. I have to manually refresh the page with the new URL. I'm not sure if the issue lies in the module or the controller. loca ...

Exploring how to utilize element.find() with class names in Angular's unit testing

Every time I run this test, I encounter the error Expected undefined to be true. it('needs to verify correct classes', function() { // doesn't give desired output expect(element.find('.exampleClass').hasClass('ng-hide&a ...

Include onload to element without running it in Puppeteer

I am currently developing a web scraping tool using Puppeteer. Once the webpage is fully loaded, I need to update the HTML code and include an onload event for certain elements. The issue is that in Puppeteer, the onload event is actually triggered automa ...

Implementing user-driven filtering in a React table

When a user clicks on the submit button, data will be loaded. If no filter is applied, all data will be displayed. const submit = async (e: SyntheticEvent) => { e.preventDefault(); const param = { ...(certificateNo && ...

Child component in Angular2 makes an observer call to its parent object

Let me try to explain this in the best way possible. I have a service that includes an observable class responsible for updating itself. This observable class needs to be pushed out to the app using the observer within the service. How can I trigger that ...

There is an issue with transmitting data from an HTML page to the server and then retrieving data from the server

Upon running this code, I encountered an issue with sending and receiving data. I kindly request assistance in correcting my code. Highlighted below is the server-side code var http = require("http") ; var fs = require("fs") ; http.createServer(function( ...

Utilize the Algolia search-insights library in conjunction with React

Trying to integrate the Search-Insights Library from Algolia with React using npm for installation instead of just adding it to the header as shown in the example. Example of implementation in React Click here for React implementation example <script ...

Halt the script if the file has not been successfully loaded

Looking for a way to halt the script until $.get() has completed executing in this code snippet. $.get("assets/data/html/navigation.html", function(response) { $('body').append(response); }); $('body').append('<div class="m ...

Efficiently convert a JSON array into an HTML table using the Jquery

Currently, I'm facing a challenge in my project. The issue arises when a query is sent to the server using jQuery, and an array is returned as a response. My struggle lies in transferring this data to a dynamic table since the column count varies with ...

Despite being listed in the entry components, HelloComponent is not actually included in the NgModule

Check out my StackBlitz demo where I am experimenting with dynamically instantiating the HelloComponent using the ReflexiveInjector. The HelloComponent is added to the app modules entryComponents array. Despite this setup, I am still encountering the foll ...

Managing promise errors by verifying the response

I am currently facing an issue where I need to handle inappropriate responses in the 'then' block of the code snippet below. getData().then(response => transformData(response)); I believe I need to implement something like this, but I am uns ...

Are the shadows in the scene being affected by a problem between DirectionalLightHelper and CameraHelper?

Currently, I am working on a complex static render in the browser using three.js and I have encountered an issue while trying to produce accurate shadows with a single THREE.DirectionalLight that represents the sun in my scene. All the geometry in another ...

When the form is submitted, any blank inputs and their corresponding hidden fields will be disabled

I created a form that has multiple input fields, and users have the option to enter values or leave them blank. Each input field is accompanied by a hidden input field which contains a specific id unique to the corresponding visible input field. To disable ...

Incorporating AngularJS to show sections of a webpage in real-time

, I am working on an angular js application in which I'm using rest services to retrieve http response data. My goal is to display different parts of the webpage conditionally based on the response data. For example, if the data in angular indicates " ...

Unable to retrieve post data from the request body

Here is my angular post request: var webCall = $http({ method: 'POST', url: '/validation', async : true, headers: { 'Content-Type': 'text/h ...

What could be causing the if/else block in my Redux Toolkit reducer to malfunction?

I'm currently working on a shopping cart feature where I need to increase the quantity of an item if it's already in the cart. If the same item with different sizes is added, they should be displayed separately. I've successfully implemented ...

Having trouble with Vue i18n and TypeScript: "The '$t' property is not recognized on the 'VueConstructor' type." Any suggestions on how to resolve this issue?

Within my project, some common functions are stored in separate .ts files. Is there a way to incorporate i18n in these cases? // for i18n import Vue from 'vue' declare module 'vue/types/vue' { interface VueConstructor { $t: an ...

Create buttons to increase or decrease values using Bootstrap and JavaScript

What is the proper way to make this button function properly? I tested adding this line of javascript code, however it prompts an alert without clicking on the buttons as well. document.querySelector(".btnminus").addEventListener(onclick,ale ...