I understand that $Broadcast()
, $Emit()
And $On()
are used to raise an event in one controller and handling in another controller. If possible, can someone just give me some real time example on the usage of above three as I am new to angular JS
?
I have gone through the following links and understand the basic usage.
http://www.binaryintellect.net/articles/5d8be0b6-e294-457e-82b0-ba7cc10cae0e.aspx
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.
The event life cycle starts at the scope on which $emit was called. All listeners listening for name event on this scope get notified. Afterwards, the event traverses upwards toward the root scope and calls all registered listeners along the way. The event will stop propagating if one of the listeners cancels it.
on is just a function that attaches an event listener. Read the docs. In my experience with AngularJS, which is admittedly limited, $on works nearly as same as the jQuery on function. The $ just signifies it's a reserved public Angular identifier.
$scope.$apply() This function is used to execute an expression in Agular. The function expression is optional and you can directly use $apply(). This is used to run watcher for the entire scope. $rootScope.$digest()
$emit
It dispatches an event name upwards through the scope hierarchy and notify to the registered $rootScope.Scope
listeners. The event life cycle starts at the scope on which $emit
was called. The event traverses upwards toward the root scope and calls all registered listeners along the way. The event will stop propagating if one of the listeners cancels it.
$broadcast
It dispatches an event name downwards to all child scopes (and their children) and notify to the registered $rootScope.Scope
listeners. The event life cycle starts at the scope on which $broadcast
was called. All listeners for the event on this scope get notified. Afterwards, the event traverses downwards toward the child scopes and calls all registered listeners along the way. The event cannot be canceled.
$on
It listen on events of a given type. It can catch the event dispatched by $broadcast
and $emit
.
Visual demo:
Demo working code, visually showing scope tree (parent/child relationship):
http://plnkr.co/edit/am6IDw?p=preview
Demonstrates the method calls:
$scope.$on('eventEmitedName', function(event, data) ... $scope.broadcastEvent $scope.emitEvent
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