how i use the $rootScope.$emit and $root.Scope.On?

I have $rootScope.$emit in my first controller and $rootScope.$on in the second controller to listen when $emit is executed.

When debugging, I see that the listener does not exist, it only exists in the other controller.

What am I doing wrong?

app.controller("Controlador", function ($scope, $window, baseServicio, $rootScope) {

    $rootScope.$on("Example", function(event) {
        console.log("hola");
    });    
});

app.controller("otherControlador", function ($scope, $window, myservicio, $timeout, $rootScope) {
    $rootScope.$emit("Example");    
});

Upvotes: 0

Views: 779

Answers (2)

georgeawg
georgeawg

Reputation: 48948

Put the listener on $scope:

app.controller("Controlador", function ($scope, $window, baseServicio, $rootScope) {    
    ̶$̶r̶o̶o̶t̶S̶c̶o̶p̶e̶.̶$̶o̶n̶(̶"̶E̶x̶a̶m̶p̶l̶e̶"̶,̶ ̶f̶u̶n̶c̶t̶i̶o̶n̶(̶e̶v̶e̶n̶t̶)̶ ̶{̶
    $scope.$on("Example", function(event) {
        console.log("hola");
    });    
});

And $broadcast from $rootScope:

app.controller("otherControlador", function ($scope, $window, myservicio, $timeout, $rootScope) {
    ̶$̶r̶o̶o̶t̶S̶c̶o̶p̶e̶.̶$̶e̶m̶i̶t̶(̶"̶E̶x̶a̶m̶p̶l̶e̶"̶)̶;̶
    $rootScope.$broadcast("Example");    
});

For more information, see

Upvotes: 1

Vinay
Vinay

Reputation: 13

There is nothing wrong in your code, make sure your "Controlador" is called first in order to register the $rootScope.$on event. After that when "otherControlador" is called it will invoke $emit and then $on will listen to $rootScope.$emit("Example").

Upvotes: 0

Related Questions