Syed Syed - 1 year ago 75
Javascript Question

How to add "active" class to "this" parent on child button is clicked and toggle "active" class if button clicked again

The below given code is just working fine apart from one more thing I need.


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


$scope.activate= function(index){

Here are the things what the above code doing:

  • The
    class is added to parent div if the child is clicked.

  • The
    class also get removed if you click another item.

The one additional function that I need is:
If the same button is clicked again then remove the
class that's already added to parent

Answer Source

You should not pass string literals into the function. Pass the value of the $index instead:

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

and in your controller, set the $scope.index to -1 if the $index is the same as your $scope.index:

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

Working plnkr:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download