AngularJS事件未从$ rootScope触发

时间:2012-11-15 12:06:13

标签: javascript angularjs

我遇到了$ rootScope。$ broadcast事件未被触发的问题:

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'];

以上内容应将{{staticText}}输出更改为'Not so Static Now',但事实并非如此。

我创建了一个JSFiddle来演示问题http://jsfiddle.net/flavrjosh/uXzTV/

这是一个更大的问题的一部分我正在尝试调试IE9在页面刷新后没有触发事件(第一次工作但刷新时 - F5或刷新按钮没有任何反应)。

任何帮助/建议将不胜感激

1 个答案:

答案 0 :(得分:22)

当$ rootScope。$ broadcast事件被触发时,似乎没有设置Child范围引起的问题。

我使用:

解决了这个问题
App.run(function($rootScope, $timeout){
    var text = 'Not So Static Now';

    $timeout(function(){
        $rootScope.$broadcast('event:staticText', text);
    }, 100);
}).$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.$apply(function(){
            $scope.staticText = args;
        });
    });

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

可以看到here

不确定这是否是最佳解决方案,但确实有效。