egurb
egurb

Reputation: 1216

Toggle Class Using Angular Directive

I want to toggle a class using the code below (thanks to Zombi for the directive he made)

I cannot figure out how to change a class of an element "B" by clicking element "A". Could you please suggest anything?

Angular

module.directive('toggleClass', function() {
return {
    restrict: 'A',
    link: function(scope, element, attrs) {
        element.bind('click', function() {
            element.toggleClass(attrs.toggleClass);
        });
    }
};

HTML

<li> <- Clicked Element
    <span toggle-class="open"></span> <-Toggled Class
</li>

Upvotes: 0

Views: 2929

Answers (2)

Rishabh Jain
Rishabh Jain

Reputation: 97

You can also look at [ng-class](https://docs.angularjs.org/api/ng/directive/ngClass,"ng-class usage") directive of angularjs.There is lot more you can do with that

Upvotes: 1

MBN
MBN

Reputation: 1006

Very simple, change your code like this:

module.directive('toggleClass', function() {
  return {
      restrict: 'A',
      link: function(scope, element, attrs) {
          element.parent().bind('click', function() {
              element.toggleClass(attrs.toggleClass);
          });
      }
  };
});

JSFiddle

Upvotes: 2

Related Questions