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);
});
});
}
}
});
Written by Janarthanan
Related protips
2 Responses
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
Best
#Angularjs
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#