[Solved-4 Solutions] Working with $scope.$emit and $scope.$on - javascript Tutorial
Problem:
How $scope.$emit and $scope.$on works ?
Solution 1:
Read Also
Solution 2:
If scope of firstCtrl
is parent of the secondCtrl
scope, your code should work by replacing $emit
by $broadcast
in firstCtrl
:
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
).
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:
Solution 3:
Solution 4:
Case 1:
$rootScope.$broadcast:-
Learn JavaScript - JavaScript tutorial - $scope.$broadcast- JavaScript examples - JavaScript programs
$rootScope
listener are not destroyed automatically. You need to destroy it using $destroy
. It is better to use $scope.$on
as listeners on $scope
are destroyed automatically i.e. as soon as $scope
is destroyed.
Or,
Learn JavaScript - JavaScript tutorial - $scope.$on- JavaScript examples - JavaScript programs
Case 2:
$rootScope.$emit:
Read Also
Learn JavaScript - JavaScript tutorial - $scope.$emit- JavaScript examples - JavaScript programs