Broadcast runs once but the event is called 2 times

Asked

Viewed 299 times

1

I have the following "broadcast" inside a "Directive":

console.log('a emitir...');
$rootScope.$broadcast('olamundo', params);

In my "controller" I have the following code:

$scope.$on('olamundo', function (event, args) {
    console.log('a escutar...');
    //aqui vai o código
});

My "olamundo" event is running 2 times, the phrase "listening..." appears 2 times on the console (due to the "console.log" in the code above).

In the "Directive" where "broadcast" is issued, the phrase 'to emit...' appears once feathers.

There is no other "broadcast" with the same name, because the 'olamundo' event is running 2 times?

  • It would be possible for you to make a functional example on Plunkr? Without seeing the rest of the code you can’t be sure what’s causing the problem.

1 answer

2


This may be an indication that you actually have two instances of your controller.

This may occur if you are mentioning the controller as part of the ui-router (or $stateProvider, if you are using ui-router) Also in the HTML document.

If this is the case, remove one of the two (the configuration of the ng-router/ui-router or the HTML entry.)

  • I am using the "angular-ui-router", but I am declaring the controller only in $stateProvider. Is there an easier way to find out if I am declaring 2 times? Or the way is to look at HTML and search?

  • I’ve noticed that this happens in any controller where I have the "$Scope. $on('olamundo'...", that is, for that you would have to make this mistake at all, but that is not the case. It could be another reason?

  • 1

    The problem was solved, it had 2 instances of the same controller, but not in HTML, but in "$stateProvider". It was using the same controller for the route "app" and for the route "app.Dashboard". The route "app" is abstract but I declare a view with the same controller. Fix the problem already and I won’t use the same controller again, it only brought problems. Thanks for the help.

  • @Filipemoraes sorry for the delay in answering you, but I’m glad you found the solution.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.