Rémi Becheras
Rémi Becheras

Reputation: 15232

$rootScope.$broadcast on $rootScope.$on: RangeError: Maximum call stack size exceeded

I want to define page title in angular like this :

a standard PageController :

angular.module('admin').controller('AdminController',
    function($scope) {

        // emit an event to rootscope
        $scope.$emit('setPageTitle','Administration');
    }
);

then in a run block :

angular.module('core').run(function($rootScope){
    $rootScope.$on('setPageTitle',function(evt,title){
        $rootScope.$broadcast('setPageTitle',title);   // The error is thrown from this line
    });
});

and finnally in the PageHeaderController :

angular.module('core').controller('PageHeaderController',
    function($scope) {

        $scope.$on('setPageTitle',function(evt, title){
            $scope.pageTitle = title;
        });
    }
);

This way, I don't need to inject $rootScope in each PageController, but just $scope that is often use for other tasks.

But I get this error at the line marked above in the second code block

RangeError: Maximum call stack size exceeded

What is wrong here ? I don't see what cause an infinit loop here because I think I just make theses steps :

Upvotes: 1

Views: 1176

Answers (3)

ssilas777
ssilas777

Reputation: 9764

Change the 'setPageTitle' event name to a different name should work, try like this

angular.module('core').run(function($rootScope){
    $rootScope.$on('setPageTitle',function(evt,title){
        $rootScope.$broadcast('setPageTitleCtrl',title);   // The error is thrown from this line - changed 'setPageTitle' to 'setPageTitleCtrl'
    });
});

Controller:

angular.module('core').controller('PageHeaderController',
    function($scope) {

        $scope.$on('setPageTitleCtrl',function(evt, title){
            $scope.pageTitle = title;
        });
    }
)

Upvotes: 3

Pandafeeder
Pandafeeder

Reputation: 36

The reason here is that $rootScope has the ability to catch events which broadcasted by itself. Thus the infinity loop happened.

Here's a very clear explanation on $rootScope's $emit, $broadcast, $on behavior

Upvotes: 2

daxeh
daxeh

Reputation: 1085

$rootScope.$on('setPageTitle',function(evt,title){
    $rootScope.$broadcast('setPageTitle',title);   // The error is thrown from this line
});

Is this the cause? Try giving distinct event names by to trace direction.

Upvotes: 1

Related Questions