titlu
titlu

Reputation: 129

Broadcast event and on are not working in angular js

I am trying to generate broadcast an event from one controller and listen to it another one. But the result is not being displayed on the DOM , though there is no error . And also when I displaying normal $scope variables from both the controllers it is working . Just the broadcast and on are not working and as there is no error so I am not ale to debugg

oneApp.controller("twoController",["$log","$scope","$rootScope",function($log,$scope,$rootScope){
var str ="sent from twoController ";
$scope.hey = 215;
$rootScope.$broadcast("hey",str);

}])

oneApp.controller("twoChildController",    ["$log","$scope","$rootScope",function($log,$scope,$rootScope){
//var str ="sent from twoController ";
//$scope.display = str;
$scope.$on("hey",function(event,str){
$scope.display = str;
});

}])

So could someone please help me to resolve this ?

Upvotes: 1

Views: 1550

Answers (2)

Riddhi Gohil
Riddhi Gohil

Reputation: 1818

Try in given way:

Define all your broadcast in some main controller like:

$rootScope.broadcast.actions = {
        hey : 'hey'
        //all broadcast
}

Broadcast send:

$rootScope.$broadcast($rootScope.broadcast.actions.hey,{str});

Broadcast receive:

$scope.$on($rootScope.broadcast.actions.hey, function (event,str){
    $scope.display = str;
});

Upvotes: 0

ram1993
ram1993

Reputation: 971

In this case, controller1 initiated first and then controller2. When controller1 initiated broadcast event has occurred and controller2 not yet initiated i.e. $on not yet registered. You can use $timeout.

var app = angular.module("myApp",[]);

//controllers declaration
app.controller('myCtrl1',function($scope, $rootScope, $timeout){
  $scope.name = "Roger";
  
  $timeout(function(){
    $rootScope.$broadcast('hey',$scope.name);
  });      
    
});

app.controller('myCtrl2',function($scope, $rootScope){
    $scope.$on('hey',function(event,name){
      $scope.name=name;
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp"> 

<div class="div1" ng-controller="myCtrl1"> 
     <span>myCtrl1 : {{name}}</span>
</div> 

<div class="div2" ng-controller="myCtrl2"> 
    <span>myCtrl2 : {{name}}</span> 
</div> 
 
</body>

Upvotes: 1

Related Questions