javascript AngularJS 事件未从 $rootScope 触发
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13397217/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
AngularJS Event not firing from $rootScope
提问by Josh Holloway
I've got a problem where $rootScope.$broadcast events aren't being fired:
我遇到了 $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'];
The above should change the {{staticText}} output to 'Not so Static Now' but it doesn't.
以上应该将 {{staticText}} 输出更改为“Not so Static Now”,但事实并非如此。
I've created a JSFiddle to demonstrate the problem http://jsfiddle.net/flavrjosh/uXzTV/
我创建了一个 JSFiddle 来演示这个问题http://jsfiddle.net/flavrjosh/uXzTV/
This is part of a bigger issue I'm trying to debug where IE9 isn't firing the events after the page gets refreshed (works first time but on refresh - F5 or the refresh button nothing happens).
这是我正在尝试调试的一个更大问题的一部分,其中 IE9 在页面刷新后没有触发事件(第一次工作但在刷新时 - F5 或刷新按钮没有任何反应)。
Any help / Advice would be appreciated
任何帮助/建议将不胜感激
回答by Josh Holloway
It appears that the problem's caused by the Child scopes not being setup when the $rootScope.$broadcast event is fired.
问题似乎是由触发 $rootScope.$broadcast 事件时未设置子作用域引起的。
I resolved the example by using:
我通过使用解决了这个例子:
App.run(function($rootScope, $timeout){
var text = 'Not So Static Now';
$timeout(function(){
$rootScope.$broadcast('event:staticText', text);
}, 100);
}).$inject = ['$rootScope'];
and:
和:
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'];
which can be seen here
可以在这里看到
Not sure if this is the best solution but it works.
不确定这是否是最佳解决方案,但它有效。