Focus on selecting just one button within Angular

By retrieving values from a database and displaying them using ng-repeat within a div:

<div ng-controller = "myTest">
    <div ng-repeat="name in names">
        <h4>{{name.name}}</h4>
            <button ng-class="{'active': isActive}" ng-click="test()" >me</button>
    </div>
</div>  

In the controller, there is:

$scope.test= function(){
    $scope.isActive = !$scope.isActive;
}

A class called isActive is defined in the CSS file which is added or removed upon clicking the button. Due to the ng-repeat, 5 result divs are created along with 5 buttons (one for each div). The issue arises when all 5 buttons receive the class change instead of just the clicked one. To achieve the desired behavior, only the clicked button should have the class applied/removed. How can this be resolved?

Answer №1

If you're looking to achieve a similar effect, you might consider implementing the following code snippet:

<div ng-controller="myTest">
    <div ng-repeat="name in names">
        <h4>{{name.name}}</h4>
        <button ng-class="{ active : name.isActive }"
                ng-click="name.isActive = !name.isActive">me</button>
    </div>
</div>

Feel free to give it a try and see if it meets your needs.

Answer №2

To effectively manage the status of each button, it is important to keep track of their individual states.

One approach is to pass a unique identifier, such as the name or any other distinguishing factor, to your function:

<div ng-controller = "myTest">
    <div ng-repeat="name in names">
        <h4>{{name.name}}</h4>
            <button ng-class="{'active': buttons[name].isActive}" ng-click="test(name)" >me</button>
    </div>
</div>  

$scope.buttons = {};

$scope.test= function(name){
    $scope.buttons[name].isActive = !$scope.buttons[name].isActive;
}

Answer №3

I have devised a solution in my plunk to address this issue without altering the original array.

The updated version of your function is as follows:

  vm.test = function(buttonIndex) {
      // Remove class if same button is pressed again
      if (vm.buttonIndex === buttonIndex) {
        vm.buttonIndex = undefined;
      } else {
        vm.buttonIndex = buttonIndex;
      }

    };

Furthermore, the corresponding HTML code should be:

 <div ng-repeat="name in main.names track by $index">
    <h4>{{name.name}}</h4>
    <button ng-class="{'active': main.buttonIndex===$index}" ng-click="main.test($index)">me</button>
  </div>

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 is the best way to distinguish between enabled buttons using Protractor?

I am facing a challenge with a table containing 20 buttons. Half of these buttons are disabled while the other half is enabled. I am looking for a way to filter out the enabled buttons and click on each of them using a for loop. The buttons that I want to ...

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 ...

When I scroll and update my webpage, the navigation header tends to lose its distinct features. This issue can be resolved

When I scroll, my navigation header changes from being transparent to having a solid color, and this feature works perfectly. However, whenever I refresh the page while already halfway down, the properties of my navigation header are reset and it reverts ...

JavaScript: set values to elements in an array

Below is the code snippet I am working with: function gotData(data){ result = data.val() const urls_kws = Object.keys(result) .filter(key => result[key].last_res > 10) var keywords = urls_kws; c ...

Shuffle the setInterval function: How to consistently rewrite with random intervals?

Seeking guidance on how to implement the following task: generate a random number after a random amount of time and then reuse it. function doSomething(){ // ... do something..... } var rand = 300; // initial random time i = setInterval(function(){ ...

Sorting an array of numbers using Javascript

Does anyone know how to properly sort an array in JavaScript? By default, the sort method doesn't work efficiently with numbers. For example: a = [1, 23, 100, 3] a.sort() The sorted values of 'a' end up being: [1, 100, 23, 3] If you hav ...

What is the process for incorporating ejs into the source attribute of an image element?

Code Snippet: <img class="card-img-top" alt="..."><%= articles.image %><img> Server Setup: const express = require('express') const app = express() const router = require('./routes/article') app ...

How to deploy a node.js app using the MEAN Stack without needing to assign a domain name

I am having an issue with my setup, where I have an AngularJS app hosted on Nginx. The app retrieves its data from a NodeJS server running on an Ubuntu 16.04 AWS instance, which is also where the frontend is being served from. When I try to access the se ...

Tips for updating state in response to changes in props

I am working on a project where I have a Parent component that renders a large form. The Parent component has child components Child1 - Child4, which are responsible for rendering input fields. Whenever the props of the Parent component change, I need to ...

Error with Google Maps Display

My goal is to achieve two things with the code snippet below: If the geocode process is unsuccessful, I want to prevent the map from being displayed (currently, I've only hidden the error message). If the geocode process is successful, I only want t ...

Error: Unexpected end of input detected (Likely due to a missing closing brace)

I've been struggling with this bug for the past two days, and it's driving me crazy. I have a feeling that I missed a brace somewhere in my script, but despite running various tests, I can't seem to pinpoint the glitch. Hopefully, your eyes ...

What could be causing the delay in response times from these unpredictable APIs within the Express server?

We are currently experiencing performance issues with our Express.js server and MongoDB database. Randomly, some API requests are taking too long to respond or timing out throughout the day. Our application is in production, hosted on two AWS instances wit ...

Convert your Node.js server URL hosted on AWS Elastic Beanstalk to HTTPS

Struggling to deploy my React JS app using AWS S3 bucket as I am new to the platform. The app communicates with a Node/Express server hosted on an Elastic Beanstalk environment. Encountered the error: Mixed Content: The page at 'https://myReactApp.s3. ...

Instructions for applying a specific style to TextFields using a theme provider

Custom transitions and colors have been added to the textfields using the makeStyles hook in the component. The issue lies in needing to define these customs every time they are used in a component. There is a desire to establish them in the theme provid ...

Combining Mongoose OR conditions with ObjectIDs

After querying my Team schema, I am receiving an array of ids which I have confirmed is correct. The issue seems to lie in the fact that both home_team and away_team are ObjectIDs for the Team Schema within my OR statement. Team.find({ 'conferenc ...

I'm having trouble locating the documents I recently saved in my mongoose model

Here is my current challenge: I am populating a collection called "fruits" with some values. Once the data has been inserted, I want to use map to console.log each fruit individually. However, during the first attempt, instead of displaying a single fruit ...

Collaborative session sharing between two node applications through Single Sign-On (SSO

I currently have a website created with express and node.js. I need to add a nodebb forum to this website, which is a separate node application. Both the main site and the forum use Facebook login, but users have to log in separately using the same Faceboo ...

Performing calculations within handsontable

Trying to figure out how to concatenate values from a handsontable grid, I stumbled upon some code on jsfiddle that caught my eye. Here is the link: http://jsfiddle.net/9onuhpn7/4/ The task at hand involves 3 columns A,B,C and an attempt to concatenate ...

Looking to display a single Angular component with varying data? I have a component in Angular that dynamically renders content based on the specific URL path

I have a component that dynamically renders data based on the URL '/lp/:pageId'. The :pageId parameter is used to fetch data from the server in the ngOnInit() lifecycle hook. ngOnInit(){ this.apiHelper.getData(this.route.snapshot.params.pageId) ...

Utilize a variable within the res.writeHeads() method in Node.js

Greetings all. I have encountered an issue that I need help with: Currently, I am using this block of code: res.writeHead(200, { "Content-Length": template["stylecss"].length, "Connection": "Close", "X-XSS-Protection": "1; mode=block", "S ...