Search code examples
angularjsangularangular-hybrid

call $emit event from angular to angularJS (publish-subscribe pattern)


I have a hybrid angular application tha uses both angularJS and angular 5.

I'm migrating a controller from angularJS to angular 5. This controller (let's call controller1) have the following code:

$rootScope.$emit('goToHomeEvent', 'Navigate to HomePage');

Then, I have another controller (let's call controller2) that subscribes the goToHomeEvent:

 $rootScope.$on('goToHomeEvent', function (event, data) {
            //Do some stuff
        });

My goal is to only migrate the controller1 to angular 5, mantaining the code of controller2 has it is, maintaining the ability to subscribe the goToHomeEvent event.

Any suggestions?


Solution

  • The solution I came up is to create global functions and associate them to them to the window variable like this:

    controller1:

    $rootScope.$emit('goToHomeEvent', 'Navigate to HomePage');
    window.goToHomeEvent(data);
    

    controller2 (in angular 2+):

    window["goToHomeEvent"] = fuction(data) {
        //do stuff here
    }