How can I make an AngularJS directive to stopPropagation?

Robert Christian picture Robert Christian · Jan 27, 2013 · Viewed 58.2k times · Source

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?

Answer

Valentyn Shybanov picture Valentyn Shybanov · Jan 27, 2013

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.