【问题标题】:How to add "active" class to "this" parent on child button is clicked and toggle "active" class if button clicked again单击子按钮时如何将“活动”类添加到“此”父级并在再次单击按钮时切换“活动”类
【发布时间】:2017-09-01 15:30:34
【问题描述】:

除了我需要的另一件事之外,下面给出的代码运行良好。

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>

控制器:

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

以下是上述代码所做的事情:

  • 如果点击子元素,active 类将添加到父 div。
  • 如果您单击其他项目,active 类也会被删除。

我需要的一个附加功能是: 如果再次单击相同的按钮,则删除已添加到父级 divactive 类。

【问题讨论】:

    标签: javascript angularjs angularjs-ng-click


    【解决方案1】:

    这可能有效:

    $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】:

        您不应该将字符串文字传递给函数。改为传递$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>
        

        如果$index 与您的$scope.index 相同,则在您的控制器中将$scope.index 设置为-1:

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

        工作 plnkr:https://plnkr.co/edit/WtkWQLcPBy5rC4Q0xNck?p=preview

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-06-22
          • 1970-01-01
          • 2022-11-18
          • 2013-03-18
          • 2015-07-27
          • 1970-01-01
          相关资源
          最近更新 更多