Search code examples
javascriptangularjsbroadcasting

AngularJS $broadcast $on


I started to learn AngularJS recently. So, I try send a message from a controller to another. I saw a lot of examples and my code is similarly, but don't work. Why $rootScope.$on don't work? Someone can help me?

HTML:

<div ng-controller="Ctrl">
    {{message}}

    <div ng-controller="Ctrl1">
        <p>Ctrl1</p>

        {{test}}
    </div>
</div>

Ctrl:

angular
    .module("app")
    .controller("Ctrl",["$rootScope","$scope",Ctrl]);

function Ctrl($rootScope,$scope){

    var test = "Bla bla bla!";
    $scope.message = test;

    $rootScope.$broadcast('aaa', test); 
}

Ctrl1:

angular
    .module("app")
    .controller("Ctrl1",["$rootScope","$scope", Ctrl1]);

function Ctrl1($rootScope, $scope){

    $rootScope.$on('aaa', function(event, args){
        console.log("This message don't appear!");
        $scope.test=args;
    });

}

Solution

  • It will not work, because Parent controller Ctrl will get register before Ctrl1 controller gets loaded. So while $broadcast event inner controller Ctrl1 listner on event haven't been registered yet.

    You could make it working by wrapping $broadcast of the event inside a $timeout function of parent controller. So it will wait get evaluated in next digest cycle.

    $timeout(function(){
       $rootScope.$broadcast('aaa', test); 
    })
    

    Demo Here