【问题标题】:calling a function in angular controller from google api present in view从视图中的google api调用角度控制器中的函数
【发布时间】:2018-01-28 15:27:10
【问题描述】:

我正在使用 google 地方详细信息 api。所以在我的 src 属性中,我放了一个名为 initMap 的回调的 google api 这是代码

<div class="tab-pane active"  id="timeline">
 <p class="lead">Location</p>
 <hr>
 <div class="row">
  <div class="col-md-1"></div>
  <div class="col-md-8">
   <h2><a href="#"></a> 
    <span>location <b style="color:black;"> kolkata</b></span></h2>
      <p></p>
      <div id="map" style="width:100%;height:400px;"></div>
      <script src="https://maps.googleapis.com/maps/api/js?key=API_KEY&libraries=places&callback=initMap"></script>
     <p></p>
    </div>
  </div>
</div>

在同一个 html 中我写了 initMap 函数

<script>
function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
      center: {lat: 22.652687, lng: 88.376882},
      zoom: 15
    });

    var infowindow = new google.maps.InfoWindow();
    var service = new google.maps.places.PlacesService(map);

    service.getDetails({
      placeId: 'ChIJvYbRT7Gd-DkR6QZQfJP9ZJg'
    }, function(place, status) {
      debugger
      if (status === google.maps.places.PlacesServiceStatus.OK) {
        var marker = new google.maps.Marker({
          map: map,
          position: place.geometry.location
        });
        google.maps.event.addListener(marker, 'click', function() {
          infowindow.setContent('<div><strong>' + place.name + '</strong><br>' +
            'Place ID: ' + place.place_id + '<br>' +
            place.formatted_address + '</div>');
          infowindow.open(map, this);
        });
      }
    });
}
</script>

只要这个函数存在于脚本标签中,它就可以完美地工作。 如何在控制器内部调用 initMap?

【问题讨论】:

    标签: javascript angularjs google-api google-places-api


    【解决方案1】:

    您不能这样调用它,而是当您使用 document.createElement('script') 加载您的应用程序时,您将在控制器中使用 javascript 加载脚本,然后连接一个 onload 事件侦听器,然后将其附加到 head 头标签中.

    最有可能:

    var script = document.createElement('script');
    script.src = 'google api script';
    script.onload = function () {
    // your onload function
    $scope.onload();
    $scope.$digest();
    };
    
    document.querySelector('head').appendChild(script);
    

    通过这种方式,您可以控制每次加载时要执行的操作。希望有帮助

    【讨论】:

      【解决方案2】:

      当您在 HTML 页面中创建一个函数时,该函数将自动分配给 window 对象,因为这是页面中包含的脚本的默认范围。

      所以从您的控制器中,您应该能够简单地调用函数,只需使用:window.initMap();

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-03-12
        • 1970-01-01
        • 2015-03-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-10-30
        相关资源
        最近更新 更多