AngularJS - stopPropagation

时间:2013-05-02 16:42:07

标签: javascript angularjs toggle stoppropagation

我真的很难实现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!');
      });
    }
  };
});

1 个答案:

答案 0 :(得分: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!');
      });
    }
  };
});