A method for applying the "active" class to the parent element when a child button is clicked, and toggling the "active" class if the button is clicked again

This code is functioning properly with just one small request I have.

HTML:

<div class="item" ng-repeat="cell in [0,1,2]" data-ng-class="{active:index=='{{$index}}'}">
    <button data-ng-click="activate('{{$index}}')">Activate Me</button>
</div>

Controller:

  $scope.activate= function(index){
      $scope.index=index;
  };

The current functionality of the above code includes:

  • The active class is applied to the parent div when its child is clicked.
  • The active class is removed if another item is clicked.

I would like to add one more feature: If the same button is clicked again, I want to remove the already added active class from the parent div.

Answer №1

Give this a try:

$scope.selectItem= function(itemIndex){
      if($scope.itemIndex == itemIndex)
          $scope.itemIndex = -1;
      else
          $scope.itemIndex = itemIndex;
};

Answer №2

angular
  .module('myApp', [])
  .controller('myCtrl', function($scope) {
    $scope.current = -1;
    $scope.toggleActive = function(current) {
      if ($scope.current === current) {
        $scope.current = -1;
      } else {
        $scope.current = current;
      }
    };
  });
.active {
  color: blue;
}
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>

<body ng-app="myApp" ng-controller="myCtrl">

  <div class="item" ng-repeat="index in [0,1,2]" ng-class="{'active': current == $index}">
    <button data-ng-click="toggleActive($index)">
      Click Me
    </button>
  </div>

</body>

</html>

Answer №3

Avoid passing string literals into the function, instead pass the value of the $index:

  <div class="item" ng-repeat="cell in [0,1,2]" data-ng-class="{'active': index == $index}">
    <button data-ng-click="activate($index)">Activate Me</button>
  </div>

In your controller, ensure that the $scope.index is set to -1 if the $index matches the current $scope.index:

 $scope.activate = function(index) {
    if (index === $scope.index) {
      $scope.index = -1;
    } else {
      $scope.index = index;
    }
  };

Check out the working plnkr: https://plnkr.co/edit/WtkWQLcPBy5rC4Q0xNck?p=preview

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

Updating a database on ASP.NET without the need to refresh the page

We are developing a user-friendly application with ASP.NET MVC that focuses on uploading pictures and rating them. The app includes two voting buttons, "like" and "dislike". https://i.sstatic.net/Z3dp5.png Whenever the like button (green) is clicked, the ...

Bring in camera from gltf

Can someone provide guidance on utilizing a camera from gltf within three-js? I am currently implementing the gltf loader as demonstrated in this example. ...

What exactly happened to my buttons when I transition to the mobile display?

Due to time constraints, I decided to save some time by utilizing a CSS template called Horizons created by Templated. This particular CSS template uses Javascript to adjust the layout for mobile devices, causing buttons to switch from inline to block for ...

What is the correct way to integrate the Ant Design library with Next.js for seamless server-side rendering?

I duplicated the official Next.js example using Ant Design at this link: https://github.com/vercel/next.js/tree/canary/examples/with-ant-design After cloning, I proceeded with npm install to install all dependencies. Then, I ran npm run dev to check if ev ...

What makes ngFor unique in Angular that allows it to not require keys like in Vue and React?

I recently delved into learning Angular a few weeks back. In Vue and React, we typically use a unique key when rendering an array of elements to optimize the rendering process, especially when there are changes in the elements' order or quantity. As a ...

Trying out a specialized validation directive in AngularJS

This validation directive is an excellent example from the official angular website. http://docs.angularjs.org/guide/forms It validates whether a text input is in number format or not. var INTEGER_REGEXP = /^\-?\d*$/; app.directive('integer ...

Ensuring Smooth Transfer: Sending Local Storage Data to MVC Controller

I'm attempting to send an array of strings from my local storage (key value) to an MVC controller. Here's the code I have so far: Inside the cshtml View file: <script> function getFavouriteBooks() { var ids = JSON.par ...

Locate and eliminate the item containing specific content

There are many <p> &nbsp </p> tags scattered throughout the description. I need to locate and delete any tags that contain only &nbsp. The description is enclosed in a container with the class name of desc_container. Below is an exampl ...

PHP - Issue with AJAX Login Functionality

I have been developing an AJAX login system and encountering an issue where it does not send any response back unless I use exit("error here") in the script. However, my goal is to return a JSON response instead. The form structure: <div id="account" ...

How to extract an integer from a particular format of ID string using JavaScript

Extracting ID variables from a text box, where these variables are subject to change: SC00021 var IdCode1 = "SC00021"; var res = IdCode1.slice(5, 7); Output: 21 Is there a way to automatically determine the position following the zeros? ...

Prevent the onClick function of the outer div from being triggered by clicking on the inner div

Similar Question: Stop parent container click event from firing when hyperlink clicked My issue is <div onClick="someJScode();"> ... <div></div> ... </div> I need to prevent someJScode() from executing when the inner di ...

Unveiling Insights from a JSON File: Data Extraction

I have a JSON file named pio2.json that contains the following data: { "controles":[{ "chart":[{ "type":"columns", "title":"Pollitos" }], "datos":[{"key":"Math","value":98}, {"key":"Physics" ...

Troubleshooting: Why isn't my CSS fixed position working for my sticky

I have a simple jQuery code snippet that is supposed to make the navigation element sticky by applying a class with position: fixed. However, I'm facing an issue on my Commerce platform where the fixed position property doesn't seem to work corre ...

Why is the jQuery class not responding to the is(:visible) selector?

Having trouble with this issue, I created a fiddle to demonstrate what I'm trying to achieve: http://jsfiddle.net/x2btM/9/ Below is the code snippet: <div id="ZodOneDragBox"> <div id="aquariusSelectedComp1" class="killSelectedComp1" sty ...

The findIndex method is failing to retrieve the accurate index

The index returned by findeIndex in an express router function is incorrect. module.exports.nearestOffices = (req, res, next) => { Order.findById(req.params.idOrder).exec() .then(order => { return Promise.all([ Promise.resolve(or ...

How can I adhere to Angular 2's naming convention for Input and Output as suggested by the styleguide?

Working with inputs and outputs while following Angular 2's styleguide naming convention Initially, my directive was defined like this: ... inputs: [ 'onOutside' ] ... export class ClickOutsideDirective { @Output() onOutside: EventEmitter ...

Nextjs: utilizing static class or employing a use function

Exploring Methods to Create a Tools Class/Function in NextJS I am considering two different approaches for this task. Using Static Class: class Tools { static titleCase(value: string) { return value.charAt(0).toUpperCase() + value.slice(1). ...

Having trouble with charts not appearing on your Django website?

I am working on a Django project where I need to integrate bar-charts using Django-nvd3. Although I have successfully displayed the bar-charts in separate projects, I am facing an issue with integrating them into my current project. Below is the code snipp ...

Increasing the size of elements with jQuery animate method

I've been utilizing the animate function in jQuery to dynamically resize a content area upon hovering over the element. Although the script is functioning correctly, I'm facing a challenge in preventing the script from resizing the content multi ...

A step-by-step guide on generating a dynamic JSON file with JavaScript

I am in need of generating a JSON structure that follows this specific format: {"content": { "properties": { "area_id": "20", "origin": "3", "axis": "1", "x_start": "00", "x_end": "99", "y_start": "00", ...