且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

AngularJS - 在多个地图的指令中异步加载谷歌地图脚本

更新时间:2023-12-05 08:55:40

你在 promise 和初始化方面有问题,我已经为你简化了

you have a problem here with promises and initialisation, i've made it cleaner for you

显然 jsfiddle 已被删除,所以这里是工作 plunker:http://plnkr.co/编辑/1NpquJ?p=预览

Apparently the jsfiddle has been removed so here is working plunker: http://plnkr.co/edit/1NpquJ?p=preview

这里是延迟加载 gmaps 的服务

here is a service for lazy load gmaps

app.service('lazyLoadApi', function lazyLoadApi($window, $q) {
  function loadScript() {
    console.log('loadScript')
    // use global document since Angular's $document is weak
    var s = document.createElement('script')
    s.src = '//maps.googleapis.com/maps/api/js?sensor=false&language=en&callback=initMap'
    document.body.appendChild(s)
  }
  var deferred = $q.defer()

  $window.initMap = function () {
    deferred.resolve()
  }

  if ($window.attachEvent) {
    $window.attachEvent('onload', loadScript)
  } else {
    $window.addEventListener('load', loadScript, false)
  }

  return deferred.promise
});

然后指令做它应该做的事情,只使用地图,不要在任何其他逻辑上加载 js 文件

then the directive does what it should do, work only with map, don't load js files on any other logic