简体   繁体   中英

AngularJs pass variables to <script>

I use AngularJs and inside a partial Google API. I need to decide marker position inside a controller.

I try to pass variable via $scope ($scope.lat & $scope.lon) but no success. What should I do?

my <script> part inside partial:

     <script>
var marker;

function myMap() {
    var myLatlng = new google.maps.LatLng({{lon}},{{lat}});
    var mapOptions = {
      zoom: 16,
      center: myLatlng
    }
    var map = new google.maps.Map(document.getElementById("googleMap"), mapOptions);

    var marker = new google.maps.Marker({
        position: myLatlng,
        title:"MyPos"
    });
        marker.setMap(map);
}

</script> 

<script src="https://maps.googleapis.com/maps/api/js?key=KEY&callback=myMap"></script>

I think the easiest way is to use global variable

window

HTML part:

 <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <script>
      window.foo = function(){
          var test = true;
          return test;
      }
    </script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="angular.js@1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>
    <script src="app.js"></script>
  </head>

Angular part:

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($window, $scope) {
    $scope.name = 'World';
    console.log($window.foo());
});

Plunker here:

http://plnkr.co/edit/OEy5S243yFMSGhMsWnjE?p=preview

And another solution is to use sessionStorage or localStorage.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM