简体   繁体   English

如何在点击角度方式添加和删除活动类

[英]How to add and remove active class on click - angular way

I am doing like this 我这样做

 <div class="tiles" ng-repeat="stat in states" ng-click="select(stat)" ng-class="{active: isActive(stat)}">
    ....
    </div>

//controller //控制器

$scope.select= function(item) {
    $scope.selected = item; 
};

 $scope.isActive = function(item) {
      return $scope.selected === item;

};

clicking on tiles it is adding active class and clicking on other tiles removing from first tiles and adding to another tiles.It is working as expected .But what i am trying to achieve is clicking on same tiles again i have to remove active class ,clicking on again i have to add like toggling .But no idea how to achieve this .Please help 点击瓷砖它正在添加活动类并点击其他瓷砖从第一个瓷砖中删除并添加到另一个瓷砖。它正在按预期工作。但我想要实现的是再次点击相同的瓷砖我必须删除活动类,单击再次,我必须添加像切换。但不知道如何实现这一点。请帮助

Update your select function to set the selected property to null if it's already selected: 更新select函数,将selected属性设置为null如果已选中):

$scope.select = function(item) {
    $scope.selected = ($scope.selected === item ? null : item); 
};

JSFiddle Example JSFiddle示例

http://jsfiddle.net/bATZ5/ http://jsfiddle.net/bATZ5/

just change your code to this: 只需将您的代码更改为:

$scope.select= function(item) {
    if (item === $scope.selected) {
        $scope.selected = null;
    } else {
        $scope.selected = item;
    }

};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM