Last active
December 29, 2016 20:24
-
-
Save fiftydegrees/e14feb972f64eb37a1b018ad9a2d2f0a to your computer and use it in GitHub Desktop.
AngularJS directive to toggle a class on any element on click (also handle #data-target attribute)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
angular.module('toggleclass.directive', []) | |
.directive('toggleClass', ['$compile', function($compile) { | |
return { | |
restrict: 'A', | |
link: function(scope, element, attrs) { | |
element.addClass('cursor pointer'); | |
element.bind('click', function() { | |
// Root element | |
toggleClassForExistingClasses(attrs.toggleClass, element); | |
// Target element | |
if (attrs.target && | |
attrs.toggleTargetClass) { | |
var targetElement = angular.element(document.querySelector(attrs.target)); | |
toggleClassForExistingClasses(attrs.toggleTargetClass, targetElement); | |
} | |
}); | |
} | |
}; | |
}]); | |
function toggleClassForExistingClasses(toggledClass, element) { | |
if (element.hasClass(toggledClass)) { | |
element.removeClass(toggledClass); | |
} else { | |
element.addClass(toggledClass); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment