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

回眸只為那壹抹淺笑 提交于 2019-12-11 06:05:58

问题


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

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

Here are the things what the above code doing:

  • The active class is added to parent div if the child is clicked.
  • The active 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 active class that's already added to parent div.


回答1:


This might work:

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



回答2:


angular
  .module('myApp', [])
  .controller('myCtrl', function($scope) {
    $scope.index = -1;
    $scope.toggle = function(index) {
      if ($scope.index == index) {
        $scope.index = -1;
      } else {
        $scope.index = index;
      }

    };
  });
.active {
  background-color: yellow;
}
<!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="cell in [0,1,2]" ng-class="{'active': index == $index}">
    <button data-ng-click="toggle($index)">
      Activate Me
    </button>
  </div>

</body>

</html>



回答3:


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

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: https://plnkr.co/edit/WtkWQLcPBy5rC4Q0xNck?p=preview



来源:https://stackoverflow.com/questions/38620253/how-to-add-active-class-to-this-parent-on-child-button-is-clicked-and-toggle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!