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

Viewed 385

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,

2 Answers

$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).

enter image description here

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

Related