2014-09-10 47 views
1

目前,我在頭部標籤頁的index.html中有該腳本。我應該將其移至app.js,對吧?無論哪種方式,你能幫助我嗎?如何修改腳本以適應app.js? 注:我使用angular.js所以app.js是angular.module如何將此腳本從index.html重寫爲angularjs app.js

<script> 
    function initialize() { 
     var mapOptions = { 
      zoom: 14, 
      center: new google.maps.LatLng(59.3332346,18.0280576) 
     }; 

     var map = new google.maps.Map(document.getElementById('map-canvas'), 
       mapOptions); 
    } 

    function loadScript() { 
     var script = document.createElement('script'); 
     script.type = 'text/javascript'; 
     script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp&' + 
       'callback=initialize'; 
     document.body.appendChild(script); 
    } 

    window.onload = loadScript; 

回答

2

移動loadScript到您的文檔的HEAD內的實際<script>標籤。不需要使用JavaScript加載腳本。

一旦你這樣做,對你的地圖創建指令:

app.directive('map', function mapDirective() { 

    return { 

     restrict: 'A', 
     scope: { 
      options: '=map' 
     }, 
     link: function link(scope, element) { 
      new google.maps.Map(element[0], scope.options); 
     } 

    } 

}); 

設置你的HTML文件,利用該指令:

<section ng-controller="MapController"> 
    <div data-map="options"></div> 
</section> 

然後終於創建控制器在傳遞地圖選項:

app.controller('MapController', function MapController($scope) { 

    $scope.options = { 
     zoom: 14, 
     center: new google.maps.LatLng(59.3332346,18.0280576) 
    } 

}); 
+0

哇謝謝!很好的答案!但我還沒有得到它的工作。 Furst我試圖實現所有它,但我的應用程序崩潰。所以我開始檢查什麼是錯誤的,我不知道什麼,但只要我將控制器輸入到controllers.js - 應用程序中斷。 它不呈現。 ('MapController',函數MapController($ scope){ }); 有什麼問題? – 2014-09-10 11:44:04

+0

對不起,我修改了包含新HTML的答案。這是因爲我們在同一個元素上有一個隔離作用域和一個控制器,並且每個都試圖創建一個新的作用域。 – Wildhoney 2014-09-10 12:51:01

+0

沒有Google Maps API的示例:http://jsfiddle.net/xy8ygcse/ – Wildhoney 2014-09-10 12:54:53