Wednesday, November 11, 2015

Angular JS: $.emit and $.on

In Angular, you sometimes need the scope/functions of another controller to be triggered by something in one controller.

For example, say you have a controller for a navigation page (Controller 1) and a Map page (controller 2) that contains changing maps. You want the navigation page to have a button that changes the map, but all of your stuff to control the Map page is in the Map controller. You can't hit those scope items or those methods.

So, you can have an onclick on the button on the Navigation page that hits the Controller 1 changeMap functions, which will $.emit 'changeMap' out.. where in Controller 2 there is an event listener $.on waiting for this to be triggered, and it will reroute you to the changeMap_Handler.

Controller 1: Navigation Page Controller Controller 2: Map Page Controller