meiwaku meiwaku - 3 months ago 15
AngularJS Question

Angular - Can't get json data from $scope

Im working on this google maps project but I can't get the json to work

angular
.module('angular-google-maps', ['uiGmapgoogle-maps'])
.controller('mainController', controller);

function controller ($scope, $http, $filter) {
$http.get('/data/markers.json').success(function(data) {
$scope.markers = data;
});

$scope.map = {
center: {
latitude: 52.339287,
longitude: 4.925805
},
zoom: 8,
markers: $scope.markers
};

$scope.options = {};

};


If I understand correctly I can just get the data by using $scope.markers right?

Answer

Unfortunate not. When you assign $scope.markers = data; you are changing the object that the variable is referencing, but $scope.map.makers is still referencing the old value (which is undefined).

Two of the simplest ways to over come this:

1) Reference the variable derectly:

$http.get('/data/markers.json').success(function(data) {
   $scope.map.markers = data;
   $scope.markers = data;
 });

2) With a watch:

$scope.markers = null;
$http.get('/data/markers.json').success(function(data) {
   $scope.markers = data;
 });

// This is fired whenever makers is changed
$scope.$watch('makers', function(value) { 
    $scope.map.markers = value; 
});
Comments