Skip to content

Instantly share code, notes, and snippets.

@gengue
Created August 20, 2015 03:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gengue/1508b7a6d6544b3d77d5 to your computer and use it in GitHub Desktop.
Save gengue/1508b7a6d6544b3d77d5 to your computer and use it in GitHub Desktop.
Angular events tutorial
//Source http://stackoverflow.com/questions/14502006/working-with-scope-emit-and-on
/*
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]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment