简体   繁体   中英

Can I call $rootScope.$emit inside a $rootScope.$on function?

I want to know if I can call a $rootScope.$emit inside a $rootScope.$on function, the reason is I have two controllers ctrl1.js and `ctrl2.js, and I would like to call a method of ctrl2.js inside my ctrl1.js

Im very new to angularjs a minute ago, here is my code, thank you,

/* Ctrl1 */
$rootScope.$on("rootScopeDisplayPage", function(event,target){
      $rootScope.$emit("CallAMethodFromCtrl2", target);
});

/* Ctrl2 */
$rootScope.$on("CallAMethodFromCtrl2", function(event, target){
               $scope.displayArticle(target);
});

$scope.displayArticle = function(articleStatus){
   /* do something */
}

its like a nested $rootScope.$on

Thank You,

$emit is used to pass data from child to parent. $rootScope is the parent scope of all the elements so it doesn't make sense to use $emit . Even though you use it, there are no parent elements to capture it.

Instead you can use $rootScope.$broadcast event to share content between controllers.

For more info refere $broadcast and $emit

 angular .module("app", []) .controller("Controller1", function($scope, $rootScope, $timeout){ var add = function(a, b) { return a + b; } $timeout(function(){ $rootScope.$broadcast("Add function", add); }, 2000); $scope.$on("Sub function", function(event, sub) { $scope.sub = sub(1, 2); }); }) .controller("Controller2", function($scope, $rootScope, $timeout){ var sub = function(a, b) { return a - b; } $scope.$on("Add function", function(event, add) { $scope.sum = add(3, 4); $timeout(function(){ $rootScope.$broadcast("Sub function", sub); }, 1000); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="app"> <div ng-controller="Controller1"> <span ng-show="!sub">Waiting for Sub function...</span> <span ng-show="sub">1 - 2 = {{ sub }}</span><br /> </div> <div ng-controller="Controller2"> <span ng-show="sum">3 + 4 = {{ sum }}</span> <span ng-show="!sum">Waiting for add function...</span><br /> </div> </div> 

There are two event broadcasting methods: $rootScope.$broadcast() and $rootScope.$emit(). the first one will send events down through the scope tree's descendants. The $emit() method will send events up through the scope tree's ancestors. When you bind to an event using the $rootScope.$on() method, your handler will be invoked regardless of how the original event was triggered (ie, broadcast vs emit).

在此输入图像描述

So you cannot use $rootScope.$emit on that since the emitted event never comes down through the scope tree.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM