0

I have code in homepage controller:

$scope.$on('showInfo', function(){
   console.log('ok');
});

And anywhere i call:

$rootScope.$broadCast('showInfo');

It's work well, but have a case following:

  1. I go to other (single page, don't reload page)

  2. Comback 'homepage', then $scope.$on will be called twice ( and if i go to other page 'N' times, $scope.$on will be called 'N' times)

I can't know reasons

:( it's very bad

Thanks for help me.

3
  • What are you trying to achieve? Please give more context. $broadcast might not be the right solution. Commented Aug 11, 2014 at 6:17
  • have you looked at Route Provider ?? You can inject controller as per your need. Commented Aug 11, 2014 at 6:18
  • could you include your controller code? Commented Aug 11, 2014 at 6:33

1 Answer 1

1

If you're not using angularjs routes as your routing mechanism, you'll end up having an additional instance of a controller after each "navigation". Old controllers won't get destroyed, so your event subscriptions stay active and process the events.

AngularJS routing prevents this by correctly "destroying" controllers, which does not remove the controllers but "deactivates" it by removing it from the $digest cycle.

It seems you're not using routing correctly or need to manage scope lifecycle by yourself (which I would'nt recommend). Second means you'll have to call $destroy() on your scope when you want it to become "deactivated".

Sign up to request clarification or add additional context in comments.

2 Comments

- call $destroy() on your scope when you want it to become "deactivated". - "deactivates" it by removing it from the $digest cycle. Can you for me a example ? Thanks very much :)
I would need to se some of your code to know why you're having multiple instances of the same controller.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.