Working with $scope.$emit and $scope.$on
To create a linkage between controllers in AngularJS, unleash an event with $scope.$emit
and capture it back with $scope.$on
. Send the event upwards to the parental scopes using $scope.$emit
and harness it with $scope.$on
. Let's get this done:
Warning: Prevent the memory from turning into Swiss cheese by exterminating listeners with the $scope.$on
return function when the scope is dismantled:
$rootScope
: For those harder to reach places
For scenarios where the controllers don't exactly see eye-to-eye (i.e., they don't share a parent-child bond), $rootScope
steps in like gossip. Use $rootScope.$broadcast
or $rootScope.$emit
to kick-start the chattering.
The service key: Your trusted vault
Sometimes, events behave like a lazy runner, taking their time to ferry data between controllers. How about a vault (a.k.a service) that holds on to the data? Let's see how that's done.
Performance: Ration your broadcasts
Be cautious with $rootScope.$broadcast
, as it loves to shout out to all scopes. Let's just say that can lead to a performance hangover. Use it sparingly and look at alternatives like services or direct method calls.
Mastering propagation
An event $emit
ted is like a homeward-bound pigeon, charting upwards through the scope hierarchy, whereas $broadcast
events are quite the explorer; they venture downwards to all child scopes.
Tidy event listeners
Listeners tied to $scope.$on
are auto-cleaned after the scope bows out. However, $rootScope
listeners need a maid. Use $on('$destroy', ...)
as your cleaning service.
Communication: Keep it simple
To avoid ending up with an event type buffet, emit a generic message with $emit
and let the parent controller be the decider. It handles specific actions and keeps things neat.
Was this article helpful?