2016-07-27 18 views
1

以下のコードは、必要なもう1つの点を除いてうまく機能しています。子ボタンの "this"親に「アクティブ」クラスを追加する方法をクリックして、再度ボタンをクリックすると「アクティブ」クラスを切り替える

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クラスも削除されます。

私は必要がある1つの追加機能は次のとおりです。 同じボタンを再度クリックされた場合は、すでに親divに追加されますactiveクラスを削除します。

答えて

1

これはうまくいくかもしれない:

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

それも助けましたが、ちょっと精巧だったので、私は他の答えに受け入れられなければなりませんでした。 – Syed

+0

申し訳ありませんが、あなたの答えは受け入れられているとマークしました;) – Syed

1

あなたは、関数に文字列リテラルを渡すべきではありません。代わりに$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と同じであれば、あなたのコントローラでは、-1 $scope.indexを設定します。plnkr作業

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

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

1

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>

関連する問題