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.
- If scope of
firstCtrl
is parent of thesecondCtrl
scope, your code should work by replacing$emit
by$broadcast
infirstCtrl
: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. alsosecondCtrl
).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 offirstCtrl
is parent of thesecondCtrl
scope:function firstCtrl($scope) { $scope.$on('someEvent', function(event, data) { console.log(data); }); } function secondCtrl($scope) { $scope.$emit('someEvent', [1,2,3]); }
Use
$rootScope.$emit
rather than$rootScope.$broadcast
regardless of the relationship between trasmitting and receiving controller. That way, the event remains within the set of$rootScope.$$listeners
whereas with$rootScope.$broadcast
the event propagates to all children scopes, most of which will probably not be listeners of that event anyway. And of course in the receiving controller's end you just use$rootScope.$on
.
No comments:
Post a Comment