What is the most efficient way to dynamically add a class to multiple elements in AngularJS using ng-click?

On my HTML page, I have 2 lists that I want to modify so that when an option is clicked, it adds a class altering the background-color of the li element to red. If the same option is clicked again, it removes the class and reverts back to white:

This is the current structure of the lists in my HTML template:

List A

<ul>
    <li>Something 1</li>
    <li>Something 2</li>
</ul>

List B

<ul>
    <li>Otherthing A</li>
    <li>Otherthing B</li>
    <li>Otherthing C</li>
</ul>

Currently, I am using individual expressions for each li element along with separate $scope variables that track true or false values. For example: $scope.otherthingaclicked = true, $scope.otherthingbclicked = true, $scope.otherthingcclicked=false, etc.

<li ng-class="expression">Otherthing A</li>

I believe there must be a more efficient way to handle this. What is a better approach to make this functionality smarter?

Answer №1

A more efficient solution exists for this problem. Utilizing Angular directives can help achieve the desired outcome:

myApp.directive("toggleClass", function() {
    return {
        link: function($scope, element, attr) {
            element.on("click", function() {
                element.toggleClass("option-selected");
            });
        }
    }
});

Next, implement it on your li elements:

<ul>
    <li toggle-class>Something 1</li>
    <li toggle-class>Something 2</li>
</ul>

Lastly, add the following CSS rules:

li.option-selected {
    background: red;
}

var myApp = angular.module("sa", []);

myApp.directive("toggleClass", function() {
  return {
    link: function($scope, element, attr) {
    element.on("click", function() {element.toggleClass("option-selected");});}});
li.option-selected {background: red;}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<ul ng-app="sa">
  <li toggle-class>Something 1</li>
  <li toggle-class>Something 2</li>
  <li toggle-class>Something 3</li>
  <li toggle-class>Something 4</li>
</ul>

Answer №2

Do you plan on utilizing (or storing) the outcome of which li elements the user has selected? If so, it may be necessary to save a boolean value for each individual li element.

//JavaScript
$scope.listA = [
    { label: "Item 1", isActive: false },
    { label: "Item 2", isActive: false },
    { label: "Item 3", isActive: false }
];

Subsequently, you can utilize a combination of ng-repeat and ng-click to manage the functionality.

<!-- HTML -->
<ul>
    <li ng-repeat="item in listA" ng-class="{ 'active': item.isActive }">
        <a href="javascript://" 
            ng-click="item.isActive = !item.isActive">{{item.label}}</a>
    </li>
</ul>

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

Will the .replaceWith() method alter the code visible to search engines?

After successfully modifying the content of specific H1 elements to not return the value from a global variable using the following code; <script type="text/javascript"> $(document).ready(function() { $("H1").filter(function() { return $(this).text ...

Leveraging AngularJS and ng-map to incorporate interactive dynamic heatmap displays

Greetings everyone! I am completely new to frontend development and have embarked on my first journey with AngularJS. I must admit, it's quite challenging and I'm still trying to wrap my head around how it all works. Currently, I'm working o ...

Tips for implementing pagination in a search result by adjusting the skip and limit values within the same query

While some may argue that this question belongs on programmers.stackexchange.com, after reviewing the Help Center of Stack Overflow, I believe it is a specific programming issue and will likely receive a better response here. I have developed a webapp usi ...

AngularJS/Bootstrap: Tips for keeping accordion-heading at the top during scrolling

I am working with a directive that contains an angularjs accordion list. Each section in the accordion-body has lengthy content. The issue I am facing is that when I expand an item and scroll down to view all the content, the header of the item goes out of ...

I'm encountering a type error stating that children are not defined when attempting to establish parent-child relationships from a flat array. What

Trying to establish a parent-child relationship between modules based on their IDs. Ran into an issue with the function I used, as it returned an error stating that children were not defined. const data = [ { module_id: "96ac027b-b5ce-4326-b5db- ...

"Seeking clarification on submitting forms using JQuery - a straightforward query

My goal is to trigger a form submission when the page reloads. Here's what I have so far: $('form').submit(function() { $(window).unbind("beforeunload"); }); $(window).bind("beforeunload", function() { $('#disconnectform&apo ...

When executing a Javascript POST request to a PHP script, it succeeds when running on

I have a simple code that works fine on my website when the PHP file is linked as "/phpcode.php", but it fails to retrieve data when I place the JavaScript request on another site and use the full link. I am currently using GoDaddy as my hosting provider. ...

The Vue v-bind:class feature does not always update immediately when the value of the binded object is changed

When utilizing Vue, it seems that developers often use v-bind:class to add dynamic classes to elements. However, in the example below, this method appears to not function as expected. //Html <div id="mainapp"> <span class="star" v-bind:class="{ ...

Conceal the results of echoing json_encode

One dilemma I encountered was passing an array from PHP to JavaScript using json_encode and ajax. The only method that seemed available was to use echo json_encode($var) This approach printed out the contents of $var on the page due to the echo statement ...

How can AJAX be used for form validation prior to submission?

Currently, I am facing an issue with validation on the client side when making an ajax cross-domain request to my PHP server page. I have a standard HTML form that posts input fields such as name, last name, and message. Here is an example of my form on th ...

What steps should I take to address the issue of fixing the classname rather than using the

<div ng-class:"{{myclass}}" role="progressbar" aria-valuenow="{{roundedtotalPerformanceCount}}" aria-valuemin="0" aria-valuemax="100" ng-style="{'width' : ( totalPerformanceCount + '%' ) }"> {{roundedtotalPerformanceCou ...

Navigating URL to switch data access

Is there a way to toggle the visibility of a div when I add #ID at the end of the URL? For instance, if I access a URL like domain.com/xxxxxx#01, then the specified div should be displayed. $(document).ready(function() { $(".toogle_button_<?php echo ...

Is it possible to set environment variables in Next.js outside of the pages directory?

Are there alternative methods for setting environment variables outside of a pages directory in NextJS? I have a utility function that defines the base API route in one centralized location. However, since this is a utility function and not associated with ...

Push function is not available in Redux

Currently, I am facing an issue while trying to use the state of a component in other components. Since this state needs to be accessed by multiple components, I have decided to switch to Redux. However, I encountered an error 'newUsers.push is not a ...

Instructions for including packages in .vue files

Within the script section of my .vue file, I have the following code: <script> import get from 'lodash.get'; ... </script> Despite trying to import lodash.get, I keep encountering an error message stating ReferenceError: ge ...

Calculating the mean value of the numbers provided in the input

I'm struggling with calculating the average of numbers entered through a prompt window. I want to display the numbers as I've done so far, but combining them to find the average is proving difficult. Here's the code I have: <html> &l ...

Challenges encountered in exporting functions with Webpack 5

Imagine having an exported function called createTableFromJSON(json) from the main file named index.js. The configuration example below adheres to the guidelines outlined in Webpack's official documentation: const config = { entry: './assets/ja ...

Require assistance with displaying a menu on a website using JQuery

Is there a way to create a menu similar to the one shown in the image below?https://i.sstatic.net/QxNPL.png To learn more about this menu, you can visit their website by clicking on this Link. I have copied some code (HTML code and links to CSS and .js fi ...

JavaScript's wildcard character, *, in a regular expression will always match something

I am currently attempting to verify whether a given string contains only uppercase letters, numbers, and underscores by utilizing the pattern matching approach with /[A-Z0-9_]*/. Despite this, executing the following code results in a return of true: /[A ...

Display a specific section depending on the user's input by utilizing either ng-if or ng-show

I have a scenario where I need to display one of two sections based on user input. If the user selects 'Daily' in the first 'type' input, I want section 1 to appear (Enter start date and hour). For any other type selection, I want secti ...