Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. Using this method seems to be the common solution.

In Angular, seems like a directive is the place to do this? 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?

like image 417
Robert Christian Avatar asked Jan 27 '13 05:01

Robert Christian


People also ask

What is event stopPropagation () in angular?

The stopPropagation() method prevents propagation of the same event from being called. Propagation means bubbling up to parent elements or capturing down to child elements.

What does event stopPropagation () do?

The event. stopPropagation() method stops the bubbling of an event to parent elements, preventing any parent event handlers from being executed. Tip: Use the event. isPropagationStopped() method to check whether this method was called for the event.

How do I invoke a directive in AngularJS?

In addition to all the built-in AngularJS directives, you can create your own directives. New directives are created by using the . directive function. To invoke the new directive, make an HTML element with the same tag name as the new directive.

What is the difference between stopPropagation and preventDefault?

preventDefault() will not allow the user to leave the page and open the URL. The event. stopPropagation() method stops the propagation of an event from occurring in the bubbling or capturing phase.


Video Answer


1 Answers

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.

like image 88
Valentyn Shybanov Avatar answered Sep 28 '22 18:09

Valentyn Shybanov