$rootScope.$emit not working

redrom picture redrom · Nov 5, 2014 · Viewed 7.5k times · Source

I'm trying to emit event in AngularJS into second controller using:

First Controller:

    $scope.checkThemeContent = function(theme) {
    console.log("Trying to get cards for theme id: " +theme.id);
    console.log(theme);

    $scope.selectedTheme = theme;

    if(theme.count_of_cards >0) {
        //$scope.$emit('detailDisplayed', {});
        $scope.displayedTemplate = 'detail';
        $rootScope.$emit('detailDisplayed', {});
    } else {
        $scope.displayedTemplate = 'empty';
    }
};

Second controller:

 $rootScope.$on('detailDisplayed', function(event, args) {
        alert('Received');
        $scope.initDataGrid();
    });

But event is not triggered.

I tried to used scope in reverse direction and it works.

Where can be problem please?

I followed this tutorial:

http://toddmotto.com/all-about-angulars-emit-broadcast-on-publish-subscribing/

Thanks for any help.

Answer

SomeKittens picture SomeKittens · Nov 5, 2014

I tried to used scope in reverse direction and it works.

Sounds to me like your code is structured to where the event is emitted before the $on handler is attached to $rootScope. Make sure the second controller has been instantiated before emitting the event.