【问题标题】:How to run a function in my Angular Scope from the `GoogleOnReady` function?如何从 `GoogleOnReady` 函数在我的 Angular 范围内运行函数?
【发布时间】:2014-02-22 18:43:20
【问题描述】:

我正在使用 Angular Maps UI,并已使用我的 API 密钥通过脚本加载从 Google API 成功将其加载回来,Google 正在正确调用我发送的回调函数。

'use strict';

angular.module('rszmeApp', [
  'ngCookies',
  'ngResource',
  'ngSanitize',
  'ngRoute',
  'ui.map'
])
  .config(function ($routeProvider) {
    $routeProvider
      .when('/', {
        templateUrl: 'views/main.html',
        controller: 'MainCtrl'
      })
      .otherwise({
        redirectTo: '/'
      });
  });

function onGoogleReady() {
    angular.bootstrap(document.getElementById("rszmeApp"), ['rszmeApp']);
}

但是,我想从 GoogleOnReady 函数在我的 Angular Scope 控制器中运行一个函数,但我不确定如何从该函数访问它。

编辑________

我这样传递回调:

<script type="text/javascript"
        src="https://maps.googleapis.com/maps/api/js?key=mykey&sensor=false&callback=onGoogleReady&libraries=geometry,drawing "></script>

 perhaps there is a way to pass the scoped function in there?

【问题讨论】:

    标签: angularjs google-maps google-maps-api-3 angular-ui


    【解决方案1】:

    您可以像这样从角度世界之外访问控制器的范围:

    angular.element("#thingy").scope();
    

    【讨论】:

    • 谢谢,但是当我这样做时,引导过程尚未完成,因此以范围结尾的 html 尚未呈现。 element("#thingy").scope() 最终未定义..
    • 误解了这个问题。为什么需要从 onGoogleReady 调用作用域上的函数?不能只在创建控制器的时候调用函数吗?
    • 不,ui-maps 指令要求加载 Google API,这就是我们将全局函数传递给 google 脚本加载标签的原因。谢谢。
    • 如果我错了,请纠正我。加载地图 api 时调用 OnGoogleReady。那时你引导角度。然后,Angular 将创建控制器作为引导的一部分。为什么不能从控制器的构造函数中调用函数?
    • 那行得通,请问我如何在控制器中最好地做到这一点?
    【解决方案2】:

    不完全确定这是否是您需要的,但您可以查看 AngularJS 中的 $broadcast 和 $on。它允许您收听事件并广播它们。 看看这个Passing Arugments to $on() in AngularJS from $emit() and $broadcast()

    【讨论】:

    • 谢谢,但我发现控制器之间的通信很好,但我需要从任何角度范围之外的回调中调用控制器函数。
    猜你喜欢
    • 2014-05-07
    • 2011-11-12
    • 2021-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-12
    • 1970-01-01
    • 2020-11-16
    相关资源
    最近更新 更多