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) {
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.
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 .
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.
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.
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'});
$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.
You could also use $document
service to trigger event
on.
Besure to include jQuery before Angular library, so jquery method will be automatically included in $element
and $document
services.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With