Last Updated: February 25, 2016
·
9.665K
· kjana83

AngularJS Toggle Class

Often we need to toggle the class by clicking the html element. Some scenario may be more than one class. Below directive helps to achieve the same.

testModule.directive("ngToggleClass", function () {
    return {
        restrict: 'A',
        compile: function (element, attr) {
            var classes = attr.ngToggleClass.split(',');
            element.bind('click', function () {
                angular.forEach(classes, function (value) {
                    (element.hasClass(value)) ? element.removeClass(value) : element.addClass(value);
                });
            });
        }
    }
});

2 Responses
Add your response

Hi Janarthanan,

Your directive is great; simple and efficient.

I suggest you could use toggleClass which is available in Angular's jqLite:
(https://docs.angularjs.org/api/ng/function/angular.element)

angular.forEach(classes, function(c) { element.toggleClass(c); });

over 1 year ago ·

Nice, but just a detail. I'd change this line:

(element.hasClass(value)) ? element.removeClass(value) : element.addClass(value);

That structure is a conditional "assignment" not an if statement.

over 1 year ago ·

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

AngularJS pages are long-lived browser apps with the same script risk as a newer single-page app. Third-party code in the template can read forms and values rendered on the page.

Security insights from Cside