0

I'm a bit confused about a situation I have, basically I need to toggle a form with the click of a button, without toggling all the forms on the page.

If I have a structure like this:

<ul>
    <li ng-repeat="item in cart"> 
        ... lots of elements ... 
        <button data-toggle data-target="myForm">Toggle form</button>
        ... some container ...
            <!-- deep nested form -->
            <form class="myForm"></form>
    </li>
</ul>

And this directive:

core.directive('toggle', [function() {
    return {
        restrict: 'A',
        link: function($scope, element, attrs) {

            element.on('click', function() {
                $('.' + attrs.target).stop().slideToggle(100);
            });
        }
    }
}]);

How do I make it so that the button won't toggle every single form in every repeated element? I somehow need to start from the li that the button resides in and then toggle the form, but exactly how can I do that in an efficient way? I was thinking about passing in an isolated scope to the directive and then use that to somehow traverse down the DOM structure and toggle the form, but it feels like that isn't even possible?

What should I do to solve my problem?

Chrillewoodz
  • 27,055
  • 21
  • 92
  • 175
  • what's the relationship between the button and the form? – sahbeewah Sep 07 '15 at 11:33
  • @sahbeewah The button just makes the form slide out. Not sure what you mean. – Chrillewoodz Sep 07 '15 at 11:37
  • Instead of a class `myForm` I would create a form ID `'#myForm'+i` where `i` increments with each element (item) added. – mccannf Sep 07 '15 at 11:37
  • @mccannf But you can only have one ID on a page so it wouldn't work since there are multiple forms. – Chrillewoodz Sep 07 '15 at 11:37
  • @mccannf Well that is a solution, but it feels a bit dirty don't you think? – Chrillewoodz Sep 07 '15 at 11:41
  • DOM relationship. All you need to do, is rather than specify the selector as the general class selector (.selector), use the form's container as context. So assuming the container happens to be a div that comes after the button: ```$(this).next('div').find('.' + attrs.target)``` ... – sahbeewah Sep 07 '15 at 11:41
  • Personally I would only use one form since they are repeating elements with same structure. No need for jQuery to do this. – charlietfl Sep 07 '15 at 11:43
  • 1
    Using the `context` argument of `jQuery()` may be the simplest way as it is, i.e. `$('.' + attrs.target, element).stop().slideToggle(100);`, but this is probably an abuse of jQuery in Angular - see [this](http://stackoverflow.com/questions/14994391/thinking-in-angularjs-if-i-have-a-jquery-background). – Nikos Paraskevopoulos Sep 07 '15 at 11:44
  • "li" is the container for both "button" and "form" elements. So you need: $(event.target).closest('li').find('form').stop().slideToggle(100); – Rustam Sep 07 '15 at 11:59
  • No one gonna post as an actual answer? – Chrillewoodz Sep 07 '15 at 18:56

0 Answers0