Can someone help me understand the way when we should use $rootScope.$on
and $scope.$on
.
I know that its mostly for hearing different scope
This is a good questions and there is an explanation for you.
$scope.on('event');
will listen to $scope.$broadcast('event')
& $rootScope.$broadcast('event')
$rootScope.on('event');
will listen to $rootScope.$broadcast('event')
& $rootScope.$emit('event')
$scope.on();
will be destroyed automatically when the controller loses it representation in view or component (getting destroyed). $rootScope.$on()
manually.$rootScope.on()
://bind event
var registerScope = $rootScope.$on('someEvent', function(event) {
console.log("fired");
});
// auto clean up `$rootScope` listener when controller getting destroy
// listeners will be destroyed by calling the returned function like registerScope();
$scope.$on('$destroy', registerScope);
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', function ($scope, $rootScope) {
var registerScope = null;
this.$onInit = function () {
//register rootScope event
registerScope = $rootScope.$on('someEvent', function(event) {
console.log("fired");
});
}
this.$onDestroy = function () {
//unregister rootScope event by calling the return function
registerScope();
}
});
$scope.on()
and $rootScope.on()
.By switching the view in this plunkr the controller will be rebinded to your view. The $rootScope.on();
event is binded every time you switch a view without destroying the event bindings of the view before. In that way the $rootScope.on()
listeners will be stacked/multiplied. This will not happen to the $scope.on()
bindings because it will be destroyed by switching the view (losing the E2E binding representation in DOM -> controller is destroyed).
$emit
& $broadcast
is:$rootScope.$emit()
events only triggers $rootScope.$on()
events. $rootScope.$broadcast()
will trigger $rootScope.$on()
& $scope.on()
events (pretty much everthing hear this event).$scope.$emit()
will trigger all $scope.$on
, all its parents (scopes in parent controllers) and $rootScope.$on()
.$scope.$broadcast
will only trigger $scope
and its children (scopes in child controllers).