Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I listen to jQuery events in AngularJS

I am rewriting a jQuery application to using AngularJS. I am using small steps, and replacing one area at a time. I am however having issues on how I can listen to jQuery's events in AngularJS.

As an example I have a $(document).trigger('doSomething') in a jQuery Widget. How can I listen to it in a AngularJS controller?

I have tried using $scope.$on('doSomething', function(){}), but that only refers to the scope of the controller. I also tried with $rootScope.$on('doSomething', function(){}), but without luck.

Is there any way where I step by step can convert my application, and just listen to the document events triggered by jQuery?

like image 449
Dofs Avatar asked May 12 '13 17:05

Dofs


2 Answers

I'm firing from the hip here, but I think jQuery events and AngularJS events are two separate systems. A quick solution might be to have a global catch-all jQuery event listener which translates the jQuery event into an AngularJS event.

Later on you might want two wrap the widget in a directive and put a more specific event-translator inside it. At that point you could also consider if you want to stick to the event-system or if an angular service might be a more suitable way for the widget to communicate with the rest of the world.

The above assumes you can't or don't want to rewrite the widget to use AngularJS mechanisms. If that's an option then just use $scope.$broadcast or $scope.$emit directly in the widget instead of $.trigger.

like image 171
Supr Avatar answered Oct 02 '22 00:10

Supr


You should see this answer: https://stackoverflow.com/a/15012542/535025

I am not sure, but i think you can't do that. Like @Supr said, they are two separated systems with separated custom events.

Try not to mix jQuery with Angular. A good recomendation is that every time you need to call $('selector').method() consider to write a directive, because it take care of the data binding.

like image 26
Guilherme Nagatomo Avatar answered Oct 02 '22 01:10

Guilherme Nagatomo