Search code examples
javascriptangularjsangularjs-scope

$emit not working while emit data from one controller to another controller in angularjs


I try to call function while emit data from one controller to another in AngularJS. But it doesn't work for me in Angular v.1.2. I need to call ctrl1 function from ctrl2. Anyone can give me some idea for this issue?

Sample code:

    <div ng-contorller="ctrl">
      <div ng-contorller="ctrl1">
      </div>
      <div ng-contorller="ctrl2">
      </div>
    </div>

function parentctrl(){

}
function ctrl1($scope){
 $scope.callfn = function(){
 console.log("success");
}
 $scope.$on('emitdata', function(event, data){
    $scope.callfn();
 })
}
function ctrl2($scope){       
 $scope.$emit('emitdata', {'key':'uu'});
}

Solution

  • Or you could use both emits and broadcasts. Child scopes emits, parents broadcast. Like so: http://plnkr.co/edit/pjGIHByzkwCeNiaVrdb6?p=preview

    app.controller("ctrl", function($scope) {
      $scope.$on('emitdata', function(event, data) {
        // This event will reach: ctrl -> ctrl1 + ctrl2
        $scope.$broadcast('broadcast-data', data);
      });
    });
    
    app.controller("ctrl1", function($scope) {
      $scope.$on('broadcast-data', function(event, data) {
        $scope.received = data;
      })
    });
    
    app.controller("ctrl2", function($scope) {
      $scope.emit = function() {
        // This event will reach: ctrl2 -> ctrl -> rootScope
        $scope.$emit('emitdata', {'key': 'uu'}); 
      };
    });