Alex Karlsson
Alex Karlsson

Reputation: 296

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

I'm trying to access a variable defined within a controller i created, so that I can loop through the list and place markers with the google maps api. I've tried a bunch of things, but I'm stuck. This is the controller:

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

And this is the part where im trying to access the variable.

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

EDIT

The answer i received worked perfectly after adding one thing (ng-if="meteorites"):

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

Upvotes: 4

Views: 188

Answers (1)

MoLow
MoLow

Reputation: 3084

you could probobly build a directive for that:

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>

Upvotes: 2

Related Questions