$ rootScope。$ $ on $ rootScope。$ on:RangeError:超出最大调用堆栈大小

时间:2015-07-21 09:08:18

标签: angularjs events event-handling angularjs-scope angularjs-rootscope

我想以角度定义页面标题,如下所示:

标准PageController

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

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

然后在一个运行块中:

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

最后在PageHeaderController

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

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

这样,我不需要在每个$rootScope中注入PageController,而只需要$scope注入其他任务。

但是我在第二个代码块中标记的行上得到了这个错误

  

RangeError:超出最大调用堆栈大小

这里有什么问题?我不知道是什么导致无限循环,因为我认为我只是做了这些步骤:

  • 小孩的发射
  • 处理rootcope并向儿童播放
  • 处理特定的孩子

3 个答案:

答案 0 :(得分:2)

更改' setPageTitle'从不同名称的事件将起作用,尝试这样

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'
    });
});

控制器:

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

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

答案 1 :(得分:2)

这里的原因是$ rootScope能够捕获自己广播的事件。因此无限循环发生了。

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

答案 2 :(得分:1)

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

这是原因吗?尝试通过跟踪方向提供不同的事件名称。

相关问题