0

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>
1
  • it worked using the ng-class but I would like to stick to the directive since I will be using it everywhere in my app Commented Apr 12, 2016 at 7:51

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

4 Comments

Indeed :) Thanks a lot!
Other thing is, what if I don't want the child element to be toggled? :) Asking just for future use...
Only change target from element.parent() to element
Oh sorry, forgot to comment, yes I figured out :) Many thanks for your help again!
1

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

1 Comment

Thanks for the hint :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.