我怎样才能使 AngularJS 指令停止传播?

我正在尝试“停止传播”,以防止点击 li 中的元素(链接)时导航栏下拉 Bootstrap 关闭。使用这种方法似乎是常见的 解决方案

在角度,似乎指令是这样做的地方? 所以我有:

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

但是方法不属于元素:

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

我把指令和

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

有什么建议吗?

58577 次浏览

stopPropagation has to be called on an event object, not the element itself. Here's an example:

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

"Currently some directives (i.e. ng:click) stops event propagation. This prevents interoperability with other frameworks that rely on capturing such events." - link

... and was able to fix without a directive, and simply doing:

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

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.

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();
});
};
});