How can I send my $scope
object from one controller to another using .$emit
and .$on
methods?
function firstCtrl($scope) { $scope.$emit('someEvent', [1,2,3]); } function secondCtrl($scope) { $scope.$on('someEvent', function(mass) { console.log(mass); }); }
It doesn't work the way I think it should. How do $emit
and $on
work?
Scope(s) can be used to propagate, dispatch event to the scope children or parent. $emit - propagates the event to parent. $broadcast - propagates the event to children. $on - method to listen the events, propagated by $emit and $broadcast.
The difference between $broadcast() and $emit() is that the former sends the event from the current controller to all of its child controllers. That means $broadcast() sends an even downwards from parent to child controllers. The $emit() method, on the other hand, does exactly opposite.
It's not possible to register an $emit or $broadcast event without $scope or $rootScope being injected in the controller. It is indeed bad practice to use $scope variables and functions since the instance of your controller is already injected inside the $scope with the controllerAs syntax.
AngularJS Scope The scope is the binding part between the HTML (view) and the JavaScript (controller). The scope is an object with the available properties and methods. The scope is available for both the view and the controller.
First of all, parent-child scope relation does matter. You have two possibilities to emit some event:
$broadcast
-- dispatches the event downwards to all child scopes,$emit
-- dispatches the event upwards through the scope hierarchy.I don't know anything about your controllers (scopes) relation, but there are several options:
If scope of firstCtrl
is parent of the secondCtrl
scope, your code should work by replacing $emit
by $broadcast
in firstCtrl
:
function firstCtrl($scope) { $scope.$broadcast('someEvent', [1,2,3]); } function secondCtrl($scope) { $scope.$on('someEvent', function(event, mass) { console.log(mass); }); }
In case there is no parent-child relation between your scopes you can inject $rootScope
into the controller and broadcast the event to all child scopes (i.e. also secondCtrl
).
function firstCtrl($rootScope) { $rootScope.$broadcast('someEvent', [1,2,3]); }
Finally, when you need to dispatch the event from child controller to scopes upwards you can use $scope.$emit
. If scope of firstCtrl
is parent of the secondCtrl
scope:
function firstCtrl($scope) { $scope.$on('someEvent', function(event, data) { console.log(data); }); } function secondCtrl($scope) { $scope.$emit('someEvent', [1,2,3]); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With