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

How to Access a div from another website using jQuery

I have a question. How can I call a div from another website using JavaScript? Here is the page: Now, I want to call the <div id="testa"> in another page. The other page is called Otherpage.html: jQuery(function($){ $(&ap ...

Efficiently handling multiple JSON objects in a single PHP function

Currently, I am working on a project that involves populating two dropdown menus where the value of one depends on the other. Specifically, I have three dropdowns - one to select a class, and the other two for selecting subjects and exams based on the sele ...

When using UI-Bootstrap, the modal window does not close when the browser's back button

Recently, I have been working on a project that involves displaying popups. I came across an issue where closing the popup using $uibModalInstance.dismiss('cancel') works perfectly fine on all pages except when trying to close it using the browse ...

The array functions properly when handwritten, but fails to work when loaded from a text file

I have been developing a password recommendation script that aims to notify users when they are using a commonly used password. In order to achieve this, I decided to load the list of common passwords from an external text file. However, it seems that the ...

Best practices for managing useEffect dependencies on page reload

I have a simple blog with articles. When a user clicks the edit button, a form is supposed to be filled with the article's data - title, description, body, and tags. I am using the useEffect hook to retrieve the data and fill the form based on the "id ...

Troubleshooting Issue with Node.js and Postman: Error encountered while attempting to

Consider the following code snippet: const fs = require('fs'); const express = require('express'); const app = express(); const bodyParser = require('body-parser') // using middleware app.use(express.json()); app.use(bodyPar ...

Transform spaces into %20 from an HTML input field by utilizing JavaScript or jQuery

Hi there, I'm encountering an issue with the input field on my website where users can enter search terms. I am currently extracting the user's input value and adding it to a URL string. jQuery("#searchButton").click(function(){ var simpl ...

Is it Possible to Insert Function from a For... in Loop?

Question: How is a function being attached to a variable's memory space without being explicitly assigned? Situation: I have developed a script to eliminate duplicate objects by comparing the values of object keys. However, after initializing the che ...

Navigating to a form within an Angular-UI uib-tab

Is it possible to access a form within a uib-tab for validation purposes? To see an example, check out this plunker: http://plnkr.co/edit/8hTccl5HAMJwUcHEtnLq?p=preview While trying to access $scope.forminside, I found that it's undefined (referring ...

What's the best method for efficiently hiding/showing a large number of DOM elements?

Imagine you have a maximum of 100 elements that remain consistent in type and format, but their content changes. These elements are connected to an input field and will update as the user types. What would be the most efficient approach for maximizing per ...

What is the process for crafting a Vuejs controlled input form?

Although I am familiar with creating controlled components in React using state, I am new to the Vue framework and would like to understand how to adapt my code from React to be compatible with Vue. My goal is to store the values of input fields in a data ...

Problems with select tag change events

I encountered an issue with select tag onChange events. When I select a value from the select tag, it should display in a textbox that is declared in the script. It works perfectly when I remove the class "input" from the select tag, but I prefer not to re ...

Customizing text appearance with innerHTML in JavaScript: A guide to styling

Below is the code I have for a header: <div id="title-text"> The Cuttlefisher Paradise </div> <div id="choices"> <ul> <li id="home"><a href="#">Home</a></li> <li id="contact">&l ...

The search box implemented in the navbar of AngularJS retrieves data to display in a table

Hey there! I'm trying to filter a table of data using a navbar search box located outside the view where the table is displayed. Struggling to figure out how to make this work. Here's the code snippet for the search box inside the navbar: <di ...

Automatically selecting a row within Material-UI's data grid using React code

Currently, I am in the process of developing a React web application and utilizing DataGrid from Material-UI by Google. The grid displays based on the user's selection from a select list (e.g., if the select list consists of fruits and the user choose ...

Creating an array of multiple divs based on numerical input

I am working on a project to show multiple divs based on the user's input number. For example, if the user selects 3, then 3 divs should be displayed. While I have successfully implemented this functionality, I need to dynamically assign IDs to each ...

An error occurs when trying to modify the classList, resulting in an Uncaught TypeError for setting an indexed property

I am attempting to modify the classes of multiple sibling elements when a click event occurs. Some of these elements may have multiple classes, but I always want to change the first class. Below is the code that I created: let classList = event.currentTa ...

How to retrieve data from an undefined table using Sequelize that is created through association

I've encountered a new challenge while working on my latest project; Imagine the tables User and Project in Sequelize have been defined. There's also a third table in the database called ProjectsUsers, and I need to retrieve data from there. T ...

Retrieving the last entity of a $resource in AngularJS using a controller

How can I access the last entity of a REST resource from within the controller? I have a factory that returns a $resource: angular.module('foo', ['ngResource']). factory('Api', ['$resource', function($resource) ...

What are the best practices for establishing a secure SignalR client connection?

While tackling this issue may not be solely related to SignalR, it's more about approaching it in the most efficient way. In C#, creating a singleton of a shared object is achievable by making it static and utilizing a lock to prevent multiple threads ...