Toggle class with ng-click on several elements

梦想的初衷 提交于 2019-11-27 11:31:43

问题


How can I toggle classes on several elements individually with ng-click?

In this question https://stackoverflow.com/a/22072110/2169327 toggling classes with a click was done like this:

CSS:

.red {
    color: red;
}

JS:

$scope.toggle = false;

HTML:

<button id="btn" ng-click="toggle = !toggle" ng-class="{'red' : toggle}">Change Class</button>

But what if I have several buttons that each should toggle its own class with ng-click?

If I set it up in this way:

HTML:

<button id="btn" ng-click="toggle = !toggle" ng-class="{'red' : toggle}">Change Class</button>
<button id="btn2" ng-click="toggle = !toggle" ng-class="{'red' : toggle}">Change Class</button>

Both buttons get toggled if I press one.

I know a workaround is to define an own ng-click event for each button (f.ex toggle1 for button1, toggle2 for button2) - but is this the best way?


回答1:


I made simple directive for testing:

module.directive('toggleClass', function() {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            element.bind('click', function() {
                element.toggleClass(attrs.toggleClass);
            });
        }
    };
});

so you can make any element toggle class you need

<button id="btn" toggle-class="active">Change Class</button>
<div toggle-class="whatever"></div>



回答2:


Depending on your requirements, you may be able to use an ng-repeat with an array representing the toggles. For example:

Your view:

<div ng-repeat="toggle in toggles">
    <button id="btn" ng-click="toggle.state = !toggle.state" ng-class="{'red' : toggle.state}">Change Class</button>
</div>

Inside your controller:

$scope.toggles = [{ state: true }, { state: false }, { state: true }];

This way you can expand on your button set by simply updating the array, or the internal array objects (should you need more complexity).




回答3:


inside controller

 $scope.stateToggle=false;
$scope.togglelasses=function(){
     $scope.stateToggle= !$scope.stateToggle;
}

in view use ng-class

 <button ng-click="togglelasses()" ng-class="stateToggle? 'active ': ' '">

add ng-class in every element where you want class active



来源:https://stackoverflow.com/questions/25141139/toggle-class-with-ng-click-on-several-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!