从Google Map回调中访问$ rootscope

时间:2014-03-11 19:12:25

标签: angularjs angularjs-scope

我很难从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']),我会收到错误。

我知道我这样做是错误的,但是如果有人可以看看并告诉我什么是错的或者给我一个更好的解决方案,我将非常感激。

谢谢!

1 个答案:

答案 0 :(得分:3)

试试这个:

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应用程序的注入器并检索所需的服务。

如果我错了,请纠正我。

相关问题