Rémi Becheras Rémi Becheras - 5 months ago 45
AngularJS Question

$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 :


  • Emit from child

  • Handle in rootscope and broadcast to children

  • Handle in a specific child


Answer

Change the 'setPageTitle' event from to a different name will 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;
        });
    }
)
Comments