1

I'm really struggling to implement stopPropagation. I'm currently working with multiple drop down menus. I would like to set it up so that when you open a menu, then click anywhere outside of it, the menu toggles off. Ideally only one menu should be open at a time, so when you open one and then click on another, the first toggles off.

Perhaps I'm approaching this in a way that is completely wrong. If so, I'd appreciate a nod in the correct direction!

Thanks!

Here is how I'm handling the open and close of the drop menus:

<a ng-click="popout.isVisible = !popout.isVisible">Drop Menu #1</a>
<ul ng-show="popout.isVisible">
    <li>This is some text.</li>
    <li>This is some text.</li>
    <li>This is some text.</li>
</ul>

<a ng-click="popout.isVisible = !popout.isVisible">Drop Menu #2</a>
<ul ng-show="popout.isVisible">
    <li>This is some text.</li>
    <li>This is some text.</li>
    <li>This is some text.</li>
</ul>

Here is some code that I found that creates a stopEvent directive, but isn't working quite the way that I need:

myApp.directive('stopEvent', function () {
  return {
    link: function (scope, element, attr) {
      element.bind(attr.stopEvent, function (e) {
          e.stopPropagation();
          alert('ALERT!');
      });
    }
  };
});
Hughes
  • 985
  • 2
  • 9
  • 29
  • You might want to check out http://stackoverflow.com/questions/12931369/click-everywhere-but-here-event – Jmr May 02 '13 at 18:50

1 Answers1

2

You've referenced the stopEvent directive there, which looks fine to me, but you're not actually using it in your HTML. Here's an extremely rudimentary implementation of what you've described:

http://jsfiddle.net/KzfSM/1/

HTML

<div ng-app="app" ng-controller="p" ng-click="hideEverything()">

    <a ng-click="popout[0].isVisible = !popout[0].isVisible" stop-event="click">Drop Menu #1</a>
<ul ng-show="popout[0].isVisible" stop-event="click">
    <li>1111</li>
    <li>This is some text.</li>
    <li>This is some text.</li>
</ul>

<a ng-click="popout[1].isVisible = !popout[1].isVisible" stop-event="click">Drop Menu #2</a>
<ul ng-show="popout[1].isVisible" stop-event="click">
    <li>2222</li>
    <li>This is some text.</li>
    <li>This is some text.</li>
</ul>


</div>

JavaScript

function p($scope) {
    $scope.popout = [ {}, {} ];
    $scope.hideEverything = function () {
        alert('hiding');
        $scope.popout[0].isVisible = false;
        $scope.popout[1].isVisible = false;
    };
}

angular
.module('app', [])
.directive('stopEvent', function () {
  return {
    link: function (scope, element, attr) {
      element.bind(attr.stopEvent, function (e) {
          e.stopPropagation();
          alert('ALERT!');
      });
    }
  };
});
Langdon
  • 19,875
  • 18
  • 88
  • 107