ng-class in AngularJs updates the class of all items within ng-repeat in the view

When applying AngularJs' ng-class, I encounter an issue where the class gets updated and applied to all items in the ng-repeat directive instead of just the specific item that was clicked. Even when using

data-target="#collapse_{{ $index }}
", it does not change only the corresponding item with the same $index.

I am puzzled about what I might be doing wrong. How can I make sure that the class change only affects the particular item that was clicked? My goal is to allow users to select and deselect a line.

This Stack Overflow post seems relevant, but I'm unsure how to adapt it to my requirements: Only add class to specific ng-repeat in AngularJS

This is the basic HTML for the header I need to modify:

<div class="panel-heading">
    <div class="container-fluid panel-container item-container">
        <div class="col-xs-1 text-left">
            <h4>
                <a data-toggle="collapse" data-target="#collapse_{{ $index }}">
                    <span class="glyphicon glyphicon-list"></span>
                </a>
            </h4>
        </div>
        <div class="col-xs-8 text-left product-header">
            <a data-toggle="collapse" data-target="#collapse_{{ $index }}">
                <span>Product Name: {{product.productName}}</span>
            </a>
        </div>
        <div class="col-xs-3 text-right">
            <span class="panel-title btn-group">
                <button type="button" id="button-selected" class="btn btn-default btn-sm abc" ng-click="addProduct(product)" ng-class="class">
                   <span class="glyphicon glyphicon-plus text-primary"></span>
               </button>
            </span>
        </div>
    </div>
</div>

Here is my CSS:

.active-product {
   background: red;
   color: green;
}

.inactive-product {
   background: none;
   color: none;
}

This is my controller method (called by the addProduct function):

$scope.class = "inactive-product";

function changeClass() {
  if ($scope.class === "active-product")
     $scope.class = "inactive-product";
  else
     $scope.class = "active-product";
};

Here is an example showing how every item gets changed: https://i.sstatic.net/KAA5J.png

Answer №1

It's important to note that there is only one $scope.class, hence why every element is utilizing it. To ensure each product has its own class property, you may need to assign a specific class to each product:

Template:

ng-class="product.class"

Controller:

function adjustClass(product) {
    if (product.class === "active-product")
        product.class = "inactive-product";
    else
        product.class = "active-product";
};

Answer №2

If you're encountering an issue where the class is being updated for all elements in an array, one solution could be to add an ng-click event that toggles an additional property to indicate if the current object is selected.

<div ng-repeat='item in productList' >
   <p ng-class='item.selected ? "active" : "default"' ng-click='toggleActive($index)'>{{ item.id }}</p>
</div>

Then, in the controller, create a function that changes the selected attribute based on the index or another preferred property.

$scope.toggleActive = function (){
 //Ensure only the clicked object has the selected attribute set to true
}

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

Automated logout feature will be enabled if no user interaction is detected, prompting a notification dialog box

Here is my working script that I found on this site. After a period of idle time, an alert message will pop up and direct the user to a specific page. However, instead of just the alert message, I would like to implement a dialog box where the user can ch ...

What is causing the malfunction of the position within this particular section?

On my website, I have a specific section where I want to showcase four products with arrows on both sides for navigation. However, I am facing an issue with the positioning of the elements. Can someone take a look and help me figure it out? Check out this ...

Troubleshooting: Issue with onclick event in vue.js/bootstrap - encountering error message "Variable updateDocument not found"

As a newcomer to frontend development, I have a basic understanding of HTML5, CSS, and Javascript. Recently, I started working on a vue.js project where I integrated bootstrap and axios. Everything seemed to be working fine until I encountered an issue whe ...

AddRegions does not function as expected

Basic code to initialize an App define(['marionette'],function (Marionette) { var MyApp = new Backbone.Marionette.Application(); MyApp.addInitializer(function(options) { // Add initialization logic here ...

Using Redux Form to set the default checked radio button in a form setting

I'm currently attempting to make a radio button default checked by using the code below: import { Field } from "redux-form"; <Field name={radio_name} component={renderField} type="radio" checked={true} value={val1} label="val1"/> <Field na ...

What is the method for implementing a timeout in axios when utilizing the proxy option?

When using Axios with the proxy option, I wanted to verify bad proxies by setting a timeout on my GET request. Here is the code snippet: let res = await axios.get(`http://somedomain.com`, { timeout: 1500, proxy: { ...

Angular Directive fails to refresh ng-model

I'm having trouble updating my ng-model within my directive Here is an example of my directive code: app.directive('DatepickerChanger', function () { return { restrict: 'E', require: 'ngModel', ...

Best practices for implementing JavaScript in JSP pages

After researching various sources, I have come across conflicting opinions on the topic which has left me feeling a bit confused. As someone new to web programming using java EE, I am looking to integrate javascript functions into my code. It appears that ...

Multiple Class Changing Effects: Hover, Fade, Toggle

I have a simple yet complex problem that I am trying to solve. I want to create links that fade in upon mouseover and fade out when the mouse moves away. Simultaneously, I want an image to slide in from the left while hovering over the links. I have manage ...

Typescript allows you to apply a filter to an array

Query: Is there a way to display a pre-selected item from my dropdown using its unique ID? Issue/Explanation: The dropdown options in my web service are dynamically fetched based on a user's ZipCode. For example, a Provider is displayed as {Pho ...

Strange behaviors when using setinterval with classes

Currently working on enhancing a slider functionality, and I have observed that everything is functioning smoothly - function Slider(element) { this.i = 0; this.element = element; var self = this; this.timer = window.setInterval(functi ...

Retrieve information from an array of objects by utilizing a separate array

There are two separate arrays provided below: ages = [20,40,60]; doctors = [{ "name": "Moruu", "age": 18, "sex": "Male", "region": "Africa" }, { "name": "Khol ...

How can I use the select2 jQuery plugin with the tags:true option to ensure that selected choices do not appear again in the dropdown menu?

Transitioning to select2 for tagging from a different plugin, I'm facing a gap that I need to address in select2's functionality. Let's consider an example. Suppose my list of choices (retrieved server-side via Ajax request) is: "Dog", "Ca ...

Is it possible to programmatically hide the Textarea and submit button for each row in a PHP-generated database table?

After spending a considerable amount of time on this project, I'm looking to incorporate a JavaScript effect (hide/unhide) into a basic submit form. Although the functionality is successful, it seems to be limited to only one row in the database tabl ...

Enhance Your Cards with Hover Zoom Text

I'm looking to place some text in front of a card hover zoom effect, but currently it appears behind the zoomed image upon hover. <div style="margin-top: 50px;" class="container imgzoom"> <div class="row ...

Discover the step-by-step guide to creating a dynamic and adaptable gallery layout using

I have encountered an issue with my gallery where the images stack once the window is resized. Is there a way to ensure that the layout remains consistent across all screen sizes? <div class="container"> <div class="gallery"> &l ...

When making jQuery Ajax calls, the $_POST variable may be empty and a warning about headers already being sent may also

I've been working on a PHP project and encountered an issue with sending data from an HTML page using jQuery Ajax to another PHP page. After numerous attempts to debug the problem, I still can't figure out why $_POST is empty when I try to echo. ...

The compatibility issue with Internet Explorer and Arabic text is impeding the functionality of jQuery AJAX

$('#search_text').keyup(function() { var search_text = document.getElementById('search_text').value; $.ajax({ url:"jx_displayautocompletelist.php", data: 'text='+search_text, success:function(result){ $ ...

Enhance and modify data with AngularJS, while also incorporating new information into the

Working on a feature where Worklists can be added and edited or deleted from local storage. Encountering an issue where after editing a worklist, it cannot be added anymore as it updates the existing worklist data that was selected for editing. (the edite ...

Tips for creating CSS Grid elements that stay fixed to the viewport

I am attempting to achieve a 100vh viewport with multiple responsive overlays on top of it. I have managed to fix the header element on the viewport using position: sticky, but I am encountering issues with making the rest work in the same way. Additional ...