Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Broadcast from Angular to a jQuery Listener

Trying to get AngularJS to broadcast a custom event that jQuery is listening for.

In the jQuery I have something similar to this:

$( document ).on( "myCustomEvent", function( event, data ) {
    $( this ).text( data.myName + ", hi there!" );
});

In the AngularJS I have something like this:

$rootScope.$broadcast('myCustomEvent', data);

Shouldn't jQuery be able to listen for the broadcast that AngularJS is broadcasting or is tied to AngularJs only with this:

$scope.$on.('myCustomEvent', function(event,data) {
like image 647
Orison Avatar asked Jan 14 '14 22:01

Orison


People also ask

What is the difference between $emit and broadcast?

The difference between $broadcast and $emit is that the former sends the event downwards from parent to child controllers, while $emit sends an event upwards from the current controller to all of its parent controllers. Both methods are available on $scope and $rootScope.

What is $emit $broadcast and $on in AngularJS?

Broadcast: We can pass the value from parent to child (i.e parent -> child controller.) Emit: we can pass the value from child to parent (i.e.child ->parent controller.) On: catch the event dispatched by $broadcast or $emit .

What is rootScope emit?

The $rootScope. $on works as a listener waiting for an event while $rootScope. $emit creates an event, so you want to put $rootScope. $on before $rootScope. $emit so that the listener can catch the event.

Is there no equivalent to scope emit () or scope Broadcast () in Angular?

Both $broadcast() and $emit() allow you to raise an event in your AngularJS application, using the event system of $scope and $rootScope . Again, there is no equivalent to this in modern Angular. If you are looking for a permanent fix during your migration to Angular, you will need an architectural level solution.


1 Answers

Demo http://plnkr.co/edit/WFERKW?p=preview

In general, event that is triggered on a DOM element will bubbling up the DOM tree to all parents of target element. So you can inject $element service in your controller and trigger event on it.

// Document as a parent of `$element` will receive this event
$(document).on('myCustomEvent', function(event, data) {
  console.log(data);
});


// In controller
$element.trigger('myCustomEvent', {myName: 'Steve Jobs'});

Attention

  1. $element service cannot be injected every where. In a controller, you can use $element, in a directive, you should use element argument from link function.

  2. You could also use $document service to trigger event on.

  3. Besure to include jQuery before Angular library, so jquery method will be automatically included in $element and $document services.

like image 50
Daiwei Avatar answered Oct 23 '22 07:10

Daiwei