javascript - Angular/JS : How do I pass a scope variable to a javascript function?

标签 javascript angularjs

我正在尝试访问在我创建的 Controller 中定义的变量,以便我可以遍历列表并使用 google maps api 放置标记。我尝试了很多东西,但我被卡住了。这是 Controller :

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="meteorites"):

<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>

关于javascript - Angular/JS : How do I pass a scope variable to a javascript function?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39230365/

相关文章:

angularjs - 在 $exceptionHandler 的装饰器中使用 Angularjs-Toaster

javascript - AngularJS $location.path(url) 不重定向

javascript - 如何在继续之前执行 Angular 中的所有 promise ?

c# - WebAPI 和 Angular JS Excel 文件下载 - 文件已损坏

javascript - getInfoByClass 的简单错误?

javascript - 如何获取 Material-UI 日期选择器值

javascript - 找出呈现页面需要多少空闲 RAM

javascript - 什么是语义 Action ?

javascript - 分配一个字符串但取回一个对象——浏览器在起作用?

javascript - 为什么我应该在单元测试中模拟 HTTP 请求?