[英]Accessing $rootscope from a Google Map callback
我在從GoogleMap API的“加載”回調中訪問Angular應用程序的$ rootscope時遇到很多困難。 我的index.html看起來像這樣:
<html>
<body ng-app="myApp">
....
<script>angular libs/controllers etc.</script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?"></script>
<script type="text/javascript">
function initialize() {
var appscope = angular.injector(['ng']).get('$rootScope');
appscope.$broadcast('MapsLoaded');
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
現在在我的控制器JS中,我有類似的內容
angular.module('myApp')
.controller('map', ['$rootScope', '$scope','$state',
function($rootScope, $scope, $state){
.....
$rootScope.$on('MapsLoaded', function() {
console.log('map loaded');
});
}
但是,控制器從不接收來自initialize方法的廣播事件。 我什至不認為angular.injector(['ng'])是正確的,但是如果我做angular.injector(['myApp']),我會得到一個錯誤。
我知道我這樣做的方式是錯誤的,但是如果有人可以看看並告訴我哪里出了問題或給我更好的解決方案,我將不勝感激。
謝謝!
嘗試這個:
function initialize() {
// access to the injector of a currently running app and get $rootScope
var appscope = angular.element('body').injector().get('$rootScope')
appscope.$broadcast('MapsLoaded');
}
在代碼中,您可以訪問默認的注入器並實例化新的$ rootScope。 使用angular.element()可以訪問當前正在運行的Angular應用的注入器並檢索所需的服務。
如果我錯了,請糾正我。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.