【发布时间】:2015-07-09 04:40:39
【问题描述】:
我有两个注入器,来自一个范围的事件永远不会到达另一个范围,即使它们应该是相同的范围......
angular.injector(['ng']).invoke(['$rootScope', function($root) {
alert('will try to be usefull');
$root.$on('bevent123', function() {
alert('useful bevent123 never happens');
});
}]);
angular.injector(['ng']).invoke(['$rootScope', function($root) {
$root.$on('bevent123', function() {
alert('bevent123 done from local injector, but we were not usefull');
});
console.log("about to $root.$broadcast('bevent123')");
window.setTimeout(function() {
$root.$broadcast('bevent123');
},1000);
}]);
更新
我的主要目标是了解谷歌地图何时加载和初始化...
var app = angular.module('module_name');
function googleCallback() {
//run does not do anything if all modules are already loaded and initialized
//angular.module('module_name').run(['$rootScope', function($root) {
angular.injector(['ng']).invoke(['$rootScope', function($root) {
console.log("about to $root.$broadcast('googleLoaded')");
$root.googleLoaded = true;
window.setTimeout(function() {
$root.$broadcast('googleLoaded');
//$root.$emit('googleLoaded');
},1000);
}]);
}
app.run(['$rootScope',function($root) {
var element = document.createElement("script");
element.type = 'text/javascript';
element.src = "https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true&libraries=places&callback=googleCallback";
element.async = true;
var domElement = document.head || document.getElementsByTagName("head")[0];
domElement.appendChild(element);
}]);
app.controller('Controller', ['$scope','$rootScope', function ($scope, $root) {
function initMaps() {
console.log("initMaps()");
}
$scope.$on('$viewContentLoaded', function() {
console.log('$viewContentLoaded');
if (!$root.googleLoaded) {
console.log("waiting for googleLoaded");
$scope.$on("googleLoaded", function() {
console.log("about to init");
initMaps();
});
} else {
initMaps();
}
});
}]);//end of app.controller('Controller'...
一切正常,直到 "about to init" 永远不会被记录到控制台并且 api 不会得到设置
【问题讨论】:
-
在超时时尝试
$root.$emit('bevent123');。 -
$emit 在 jsfiddle 上具有相同的行为
-
从注入器到控制器之间没有关系,所以rootScope.emit或广播在scope.on上不起作用,尝试使用$rootScope.$on()
-
@ritesh 实际的问题是可以有多个“
$rootScope”
标签: angularjs angularjs-scope angular-broadcast