Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop $broadcast events in AngularJS?

Is there a built in way to stop $broadcast events from going down the scope chain?

The event object passed by a $broadcast event does not have a stopPropagation method (as the docs on $rootScope mention.) However this merged pull request suggest that $broadcast events can have stopPropagation called on them.

like image 633
Noah Freitas Avatar asked Mar 14 '13 21:03

Noah Freitas


People also ask

How to stop broadcasting event in javascript?

Use the stopPropagation() method to handle this" stopPropagation: The event will complete dispatch to all listeners on the current EventTarget before event flow stops.

How to call rootScope function in AngularJS?

You'll have to declare the $rootScope. logout function in the module's run block instead. For more information on this, read the Module Loading & Dependencies part of the angular docs. Where are you registering the $rootScope.

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.


1 Answers

Snippets from angularJS 1.1.2 source code:

$emit: function(name, args) {     // ....     event = {         name: name,         targetScope: scope,         stopPropagation: function() {             stopPropagation = true;         },         preventDefault: function() {             event.defaultPrevented = true;         },         defaultPrevented: false     },     // .... }  $broadcast: function(name, args) {     // ...     event = {         name: name,         targetScope: target,         preventDefault: function() {             event.defaultPrevented = true;         },         defaultPrevented: false     },     // ... } 

As you can see event object in $broadcast not have "stopPropagation".

Instead of stopPropagation you can use preventDefault in order to mark event as "not need to handle this event". This not stop event propagation but this will tell the children scopes: "not need to handle this event"

Example: http://jsfiddle.net/C8EqT/1/

like image 77
kostik Avatar answered Sep 28 '22 05:09

kostik