MonkRocker
MonkRocker

Reputation: 309

Find all elements in an Angular directive

I am trying to implement something similar to an accordion in pure Angular.

I have a list of FAQs, with the answers hidden (via css display: none;). I want it to work so that when you click on a question, then answer appears. If you click on the question again, the answer hides again.

That all works fine using the following directive:

.directive('toggleOpen', function toggleOpen() {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            element.bind('click', function () {
                if(element.parent().children().hasClass('open')) {
                    element.parent().children().removeClass('open');
                } else {
                    element.parent().children().addClass('open');
                }
            });
        }
    }
});

So the reason there's a bunch of parent().children() nonsense is the part I couldn't get working.

Let's say you have 2 Questions, 1 and 2. When the page loads, both answers are hidden. User clicks question 1, and answer 1 unhides. Currently, when you click question 2, answer 2 unhides, which is also correct - but I only ever want ONE answer open at a time. So if answer 1 is showing and the user clicks question 2, I want answer 1 to hide, and answer 2 to show.

I have a css class 'open' I am applying to unhide answers. So basically - how can I find ALL elements having the class 'open' and remove it, then apply it to the element the user clicked on?

Is there a "pure" angular way to do this?

TIA

Upvotes: 0

Views: 1593

Answers (1)

Jesse Houchins
Jesse Houchins

Reputation: 66

you could do it all with template logic, no directive needed:

<section ng-class="{open: selected=='q1'}">
  <question ng-click="selected='q1'" ></question>
  <answer></answer>
</section>
<section ng-class="{open: selected=='q2'}">
  <question ng-click="selected='q2'" ></question>
  <answer></answer>
</section>
<section ng-class="{open: selected=='q3'}">
  <question ng-click="selected='q3'" ></question>
  <answer></answer>
</section>

Upvotes: 1

Related Questions