简体   繁体   中英

AngularJS Event not firing from $rootScope

I've got a problem where $rootScope.$broadcast events aren't being fired:

App.run(function($rootScope){
    var text = 'Not So Static Now';
    $rootScope.$broadcast('event:staticText', text);
}).$inject = ['$rootScope'];


App.controller('Ctrl1', function($scope, $rootScope) {
   $scope.staticText = "Static Text";

    var things = [
        'AngularJS',
        'StackOverflow',
        'JSFiddle'
    ];

    $scope.$emit('event:things', things);

    $scope.$on('event:staticText', function(e, args){
        $scope.staticText = args;
    });

}).$inject = ['$scope', '$rootScope'];

The above should change the {{staticText}} output to 'Not so Static Now' but it doesn't.

I've created a JSFiddle to demonstrate the problem http://jsfiddle.net/flavrjosh/uXzTV/

This is part of a bigger issue I'm trying to debug where IE9 isn't firing the events after the page gets refreshed (works first time but on refresh - F5 or the refresh button nothing happens).

Any help / Advice would be appreciated

It appears that the problem's caused by the Child scopes not being setup when the $rootScope.$broadcast event is fired.

I resolved the example by using:

App.run(function($rootScope, $timeout){
    var text = 'Not So Static Now';

    $timeout(function(){
        $rootScope.$broadcast('event:staticText', text);
    }, 100);
}).$inject = ['$rootScope'];

and:

App.controller('Ctrl1', function($scope, $rootScope) {
    $scope.staticText = "Static Text";

    var things = [
        'AngularJS',
        'StackOverflow',
        'JSFiddle'
    ];

    $scope.$emit('event:things', things);

    $scope.$on('event:staticText', function(e, args){
        $scope.$apply(function(){
            $scope.staticText = args;
        });
    });

}).$inject = ['$scope', '$rootScope'];

which can be seen here

Not sure if this is the best solution but it works.

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