Broadcasting AngularJS events from vanilla JavaScript

In this short post I’ll show how to invoke AngularJS from plain JavaScript. Why would you want to do this? Well, in certain edge cases you might need to catch events in plain JS but still want to handle them back inside your Angular app. For example on an SVG element mouse event..

Say you have an Angular controller named SomeCtrl and that’s where you want to handle the event. You’ll need an element you’ll be able to target either by an id or by a class, and it needs to be scoped with a controller like this:

Next, say you have something like onmouseover=”onMouseOver()” on one of your HTML/SVG elements:

You’ll need to add a $scope.$on listener for the “mouse-over-event” event inside your SomeCtrl controller. Your Angular app will catch the broadcast, you’ll be back inside the Angular scope and digest loop and you’ll be able to handle the event further from there.

That’s it!