Last Updated: February 25, 2016
·
9.402K
· 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 ·