Ali Cuche
Ali Cuche

Reputation: 11

Angularjs, how to prevent bind twice in controller

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.

Upvotes: 0

Views: 95

Answers (1)

Sabacc
Sabacc

Reputation: 789

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".

Upvotes: 1

Related Questions