Manipulating classes within ng-class in AngularChanging classes in ng-class dynamically

Featuring multiple elements with an ng-class that behaves similarly to a ternary operator:

ng-class="$ctrl.something ? 'fa-minus' : 'fa-plus'"

To access these elements, we can compile all the ones with fa-minus and store them in a list:

const elementList = document.querySelectorAll('.fa-minus');

I am wondering if it's possible to alter the contents of ng-class. For instance, changing all instances of fa-minus to fa-square.

I have attempted various methods like removing and adding classes:

    const elementList = document.querySelectorAll('.fa-minus');
    document.forEach(document=> document.classList.remove('.fa-minus'));
    document.forEach(document=> document.classList.add('fa-square'));

This approach didn't work, presumably due to the original being defined within an ng-class rather than a traditional CSS class.

The goal is not to edit the original ng-class, but to modify it only within a function that generates an export file

Is there a solution to this issue?

Answer №1

When using AngularJS, it is best to avoid direct DOM manipulation. Instead, use the following code in an angular way.

HTML

ng-class="$ctrl.getClass()"

Controller

var $ctrl = this;
var MINUS = 'fa-minus';
var PLUS = 'fa-plus';

getClass () {
   return $ctrl.something ? MINUS : PLUS
}

changeMinusClass(newClass) {
   MINUS = newClass
}

onClickOfSomething () {
   this.changeMinusClass('fa-square')
}

Answer №2

To ensure proper functionality, it is recommended to first remove a class before adding a new one using the remove() and add() methods. It is advised not to use 'document' as the name for a variable, and also avoid using the same name for both a parameter and handler function.

Here is an example illustrating how this can be implemented:

var elements = document.querySelectorAll('span');
elements.forEach(item => {
  item.classList.remove('fa-minus');
  item.classList.add('fa-square');
});

// for visual confirmation
document.querySelectorAll('span').forEach(span => console.log(span.getAttribute('class')));
<span class="fa-minus">Test 1</span>
<span class="fa-minus">Test 2</span>

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 causes an image's size to change when it floats within the parent container?

There seems to be a height mismatch issue between the container and the image inside it when the parent is floated, but not the child. However, when both are given the float property, the height matches perfectly. Why is this? <div class="parent">&l ...

Updating the variables of HTML components using JavaScript after making an AJAX request

I am using ajax to fetch a list of user data. But after this ajax call, I need to display the data in an HTML structure like a datasheet for each user. My question is how can I store the HTML code in a functional and elegant way to maintain readability and ...

Audio in A-Frame does not function properly when in VR mode

My friend and I are collaborating on a small project involving a VR simulation that requires audio instructions. While everything functions smoothly in the web version and even on mobile devices, we encountered an issue when switching to VR mode on mobile ...

The concept of AngularJS bi-directional binding

Can a two-way binding be created between the parent scope and my directive's isolated scope without using my directive's attributes? The '=' sign establishes a two-way binding, but not in a direct way: it does not take the specified va ...

Sharing data between AngularJS and D3 with JSON - a guide

When working on my application controller, I typically send a request to my API. This is what it usually looks like: .state('state1', { url: '/datas/:id', templateUrl: 'myurl.com', title: 'title', ...

Adding Node.js Express responses to a running list

I have a situation in one route where I am using multiple instances of res.send. Is there a way to combine them all into one and then send the aggregated list at the end? The format I prefer is as follows: { "writer": {success message}, "archive": {succes ...

Having trouble with sending a post request through ajax

Whenever I try to initiate an Ajax request upon clicking a button, the request never seems to get executed. Below is the snippet of my HTML code : <!DOCTYPE html> <html lang="en"> <head> <title>User Form</title> ...

What is the best way to combine a collection of strings and HTML elements in a React application?

I am facing a challenge with my list of names. I typically use .join to add commas between each name, but one specific item in the list needs to display an icon of a star next to it based on a certain condition. The issue is that using join turns everyth ...

AngularJS - Trouble loading directive

I'm facing some challenges with a custom directive I've created and it's not functioning as expected. Below is the code for my directive: angular .module('thermofluor') .directive('myCustomer', function() { return ...

JavaScript - Retrieve a nested property within an object using an array of strings

I possess an object in the following format { metadata: { correlationId: 'b24e9f21-6977-4553-abc7-416f8ed2da2d',   createdDateTime: '2021-06-15T16:46:24.247Z' } } and I possess an array containing the properties I wish to re ...

Once the form has been loaded without any information, go ahead and submit

I have created my index.php file with the following code: <script src="js/jquery-1.9.1.js"></script> <script> $(document).ready(function(){ $("#sload").load('save1.php',function(forma){ $(".csave").click(function(){ ...

jQuery: changing the order of list elements with the eq method

I've been tackling a challenge with designing a navigation bar that consists of 3 items. The goal is to have the clicked item move to the center position on the horizontal navbar while re-arranging the order. Here's the code snippet I've com ...

Adding a checkbox to a div without checking it - checkbox remains untouched

My first jQuery To Do List is almost complete! Each list item has a checkbox that, when checked, moves the item to the Done section. The only issue I'm facing is that the checkbox always remains unchecked. I've tried using .prop() but it doesn&ap ...

Setting a one-month date range in Bootstrap Material date picker - a simple guide

Is it possible to configure a 1-month date range in the Bootstrap Material date picker? Check out this link for more information ...

What could be causing my externally hosted React component to malfunction when being imported via NPM?

After successfully creating a standalone component within my original project, I decided to explore the possibility of releasing it as an NPM module. To kick off this process, I attempted to load the library from another repository using NPM in a new proje ...

Automated updating feature with jQuery

Is there a way to use jQuery code to automatically refresh a page after navigating back in the browser history? Here is an example of what I have tried: jQuery(".form_" + form_count).html("<div id='message'></div>") jQuery('#me ...

Welcome Message using Discord.js V13

As a newcomer to bot creation, I am facing an issue with my welcome message in discord.js v13. Previously working in v12, I am now encountering difficulties sending a message to a specific channel when a user joins the server. After some investigation, I r ...

Tips for using an array as a jQuery selector in JavaScript

Managing an element with an array id id="x[]" can be tricky when it comes to dynamically changing content based on database entries. This specific element is essentially a delete button for removing table rows from the database. <div align="center" id= ...

What is the best way to output a received HTML page from the server?

I'm currently working on printing an HTML page that was generated using Node.js on my server. After sending the page to the client side as a response to an AJAX request, I have stored it in a JavaScript variable. var resp_json = printRequest.getRespo ...

Managing Express Sessions: Best Practices

I am currently working on handling authentication sessions in a Node.js, Express, Passport app. Despite using express-session and registering new users, the authentication still doesn't work. Below is the code snippet for the local strategy: // Loca ...