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
        $scope.changeMap = function () {
            $rootScope.$emit('changeMap', { fromState: $state.current.name });
            $state.go('locations');
        }   
Controller 2: Map Page Controller
    $rootScope.$on("changeMap", changeMap_Handler);  // passes it to the handler function

    // here is the handler function
    function changeMap_Handler(event, attrs) {
        $scope.changingMap = true;
        $rootScope.changingMap  = $scope.changingMap ;
        if (attrs.fromState === "someStateVariable") {
            $scope.variable = true;
        }
    }