简体   繁体   English

如何将AngularJS指令设置为stopPropagation?

[英]How can I make an AngularJS directive to stopPropagation?

I am trying to "stopPropagation" to prevent a Twitter Bootstrap navbar dropdown from closing when an element (link) inside an li is clicked. 我试图“停止传播”以防止在点击li中的元素(链接)时关闭Twitter Bootstrap导航栏下拉列表。 Using this method seems to be the common solution . 使用这种方法似乎是常见的解决方案

In Angular, seems like a directive is the place to do this? 在Angular中,似乎是一个指令就是这样做的地方? So I have: 所以我有:

// do not close dropdown on click
directives.directive('stopPropagation', function () {
    return {
        link:function (elm) {            
            $(elm).click(function (event) {                
                event.stopPropagation();
            });
        }
    };
});

... but the method does not belong to element: ...但该方法不属于元素:

TypeError: Object [object Object] has no method 'stopPropagation'

I tie in the directive with 我指的是指令

<li ng-repeat="foo in bar">
  <div>
    {{foo.text}}<a stop-propagation ng-click="doThing($index)">clickme</a>
  </div>
</li>

Any suggestions? 有什么建议?

I've used this way: Created a directive: 我用过这种方式:创建了一个指令:

    .directive('stopEvent', function () {
        return {
            restrict: 'A',
            link: function (scope, element, attr) {
                if(attr && attr.stopEvent)
                    element.bind(attr.stopEvent, function (e) {
                        e.stopPropagation();
                    });
            }
        };
     });

that could be used this way: 可以这样使用:

<a ng-click='expression' stop-event='click'>

This is more generic way of stopping propagation of any kind of events. 这是阻止任何类型事件传播的更通用方法。

"Currently some directives (ie ng:click) stops event propagation. This prevents interoperability with other frameworks that rely on capturing such events." “目前一些指令(即ng:click)会阻止事件传播。这会阻止与依赖于捕获此类事件的其他框架的互操作性。” - link - 链接

... and was able to fix without a directive, and simply doing: ......并且能够在没有指令的情况下修复,并且只是做:

<a ng-click="doThing($index); $event.stopPropagation();">x</a>

stopPropagation has to be called on an event object, not the element itself. 必须在事件对象上调用stopPropagation ,而不是元素本身。 Here's an example: 这是一个例子:

compile: function (elm) {
    return function (scope, elm, attrs) {
        $(elm).click(function (event) {
            event.stopPropagation();
        });
    };
}

Here's a simple, abstract directive to stop event propagation. 这是一个简单的抽象指令来停止事件传播。 I figure it might be useful to someone. 我认为它可能对某人有用。 Simply pass in the event you wish to stop. 只需通过您想要停止的活动即可。

<div stopProp="click"></div>

 app.directive('stopProp', function () { return function (scope, elm, attrs) { elm.on(attrs.stopProp, function (event) { event.stopPropagation(); }); }; }); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM