簡體   English   中英

Angular / JS:如何將范圍變量傳遞給javascript函數?

[英]Angular/JS: How do I pass a scope variable to a javascript function?

我正在嘗試訪問我創建的控制器中定義的變量,這樣我就可以遍歷列表並使用google maps api放置標記。 我嘗試了很多東西,但是我被卡住了。 這是控制器:

app.controller('MainController', ['$scope', 'meteorite', function($scope, meteorite) { 
meteorite.success(function(data) { 
$scope.meteorites = data;});
}]);

這是我試圖訪問變量的部分。

<div id="map">
</div>

<div class="main" ng-controller="MainController">
  <div id="stuff" ng-repeat="meteorite in meteorites">
    <h1>{{meteorite.name}} : {{meteorite.mass | number}}</h1> 
  </div>
</div>

<script>
  var map;
  var myLatLng = {lat: -25.363, lng: 131.044};

  function initMap() {
    map = new google.maps.Map(document.getElementById('map'), {
      center: myLatLng,
      zoom: 10
    });

    for (var i = 0; i < [This is where i want to access meteorites]; i++) {
      var marker = new google.maps.Marker({
        position: {meteorites[i].lat, meteorites[i].long},
        map: map
      });
    }
  }
</script>

編輯

我收到的答案在添加一件事(ng-if =“隕石”)后完美地完成了:

<g-map ng-if="meteorites" meteorites="meteorites"></g-map> 

你可能會為此建立一個指令:

 angular.module('app', []) .controller('MainController', ['$scope', function($scope) { $scope.meteorites = [{name:'aaa', mass:1, lat: -25.363, long: 131.044}]; }]) .directive('gMap', function() { return { restrict: 'E', replace: true, template: '<div style="height:200px;"></div>', scope: {meteorites: '='}, link: function(scope, element) { var myLatLng = {lat: -25.363, lng: 131.044}, map = new google.maps.Map(element[0], { center: myLatLng, zoom: 10 }); angular.forEach(scope.meteorites, function(meteorit) { var marker = new google.maps.Marker({ position: new google.maps.LatLng(meteorit.lat, meteorit.long), map: map }); }) } } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <script src="https://maps.googleapis.com/maps/api/js"></script> <div id="map"> </div> <div class="main" ng-app="app" ng-controller="MainController"> <div id="stuff" ng-repeat="meteorite in meteorites"> <h1>{{meteorite.name}} : {{meteorite.mass | number}}</h1> </div> <g-map meteorites="meteorites"></g-map> </div> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM