AngularJS事件未从$ rootScope触发

Jos*_*way 9 javascript angularjs

我有一个问题,$ rootScope.$广播事件没有被解雇:

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'];
Run Code Online (Sandbox Code Playgroud)

上面应该将{{staticText}}输出更改为'Not so Static Now',但事实并非如此.

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

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

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

Jos*_*way 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'];
Run Code Online (Sandbox Code Playgroud)

和:

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'];
Run Code Online (Sandbox Code Playgroud)

这可以在这里看到

不确定这是否是最好的解决方案,但它确实有效.

  • 添加`$ timeout`提供程序给广播为我做了! (2认同)