1

我真的很难实现 stopPropagation。我目前正在使用多个下拉菜单。我想对其进行设置,以便当您打开菜单,然后单击其外部的任意位置时,菜单会关闭。理想情况下,一次只能打开一个菜单,因此当您打开一个然后单击另一个时,第一个会关闭。

也许我正在以一种完全错误的方式处理这个问题。如果是这样,我将不胜感激朝正确的方向点头!

谢谢!

这是我处理下拉菜单的打开和关闭的方式:

<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>

这是我发现的一些代码,它们创建了一个 stopEvent 指令,但并没有按照我需要的方式工作:

myApp.directive('stopEvent', function () {
  return {
    link: function (scope, element, attr) {
      element.bind(attr.stopEvent, function (e) {
          e.stopPropagation();
          alert('ALERT!');
      });
    }
  };
});
4

1 回答 1

2

您在stopEvent那里引用了该指令,这对我来说看起来不错,但您实际上并没有在 HTML 中使用它。这是您所描述的内容的非常基本的实现:

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!');
      });
    }
  };
});
于 2013-05-02T17:15:48.803 回答