除了我需要的另外一件事之外,下面给出的代码工作正常。
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
课程也会被移除。 我需要的另一项功能是:
如果再次点击相同的按钮,则删除已添加到父active
的{{1}}类。
答案 0 :(得分:1)
这可能有效:
$scope.activate= function(index){
if($scope.index == index)
$scope.index = -1;
else
$scope.index = index;
};
答案 1 :(得分: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>
如果$scope.index
与$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
答案 2 :(得分: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>