AngularJS event does not fire from $ rootScope

I have a problem when $ broadcastScope. $ broadcast events do not fire:

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 output of {{staticText}} to "Not Static Now", but it is not.

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

This is part of the bigger problem that I am trying to debug when IE9 does not fire events after the page is refreshed (it works the first time, but when it refreshes - F5 or the refresh button nothing happens).

Any help / advice would be appreciated

+8
javascript angularjs
source share
1 answer

It seems that the problem caused by the Child scope is not configured when the $ rootScope event is fired. $ broadcast.

I resolved this example 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.

+21
source share

All Articles