简体   繁体   中英

$rootScope.$emit not working

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.

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.

Remember: emit goes up the prototype chain, broadcast goes down. If you are already at the top (ie $rootScope ) it can't go any higher. Use $broadcast to get the event to fire across the board.

$rootScope.$broadcast('detailDisplayed');

Check this article:

https://blog.safaribooksonline.com/2014/04/08/refactoring-angularjs-get-hands-filthy/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM