Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
979 views
in Technique[技术] by (71.8m points)

angularjs - Toggle class with ng-click on several elements

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...