Javascript 如何加上「;主动的;类别改为;这";单击“父对象在子对象上”按钮并切换;主动的;如果再次单击按钮,则初始化

Javascript 如何加上「;主动的;类别改为;这";单击“父对象在子对象上”按钮并切换;主动的;如果再次单击按钮,则初始化,javascript,angularjs,angularjs-ng-click,Javascript,Angularjs,Angularjs Ng Click,下面给出的代码只是工作良好,除了一件事我需要 HTML: 以下是上述代码的作用: 如果单击子级,则将活动的类添加到父div中 如果单击另一项,活动的类也将被删除 我需要的另一个功能是: 如果再次单击同一按钮,则删除已添加到父级div的活动类,这可能会起作用: $scope.activate= function(index){ if($scope.index == index) $scope.index = -1; else $s

下面给出的代码只是工作良好,除了一件事我需要

HTML:

以下是上述代码的作用:

  • 如果单击子级,则将
    活动的
    类添加到父div中
  • 如果单击另一项,
    活动的
    类也将被删除
我需要的另一个功能是: 如果再次单击同一按钮,则删除已添加到父级
div

活动类,这可能会起作用:

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

不应将字符串文本传递到函数中。改为传递
$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>
工作plnkr:

angular
.module('myApp',[])
.controller('myCtrl',函数($scope){
$scope.index=-1;
$scope.toggle=函数(索引){
如果($scope.index==index){
$scope.index=-1;
}否则{
$scope.index=索引;
}
};
});
.active{
背景颜色:黄色;
}

激活我
$scope.activate= function(index){
      if($scope.index == index)
          $scope.index = -1;
      else
          $scope.index = 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>
 $scope.activate = function(index) {
    if (index === $scope.index) {
      $scope.index = -1;
    } else {
      $scope.index = index;
    }
  };