Angular - 无法从$ scope获取json数据

时间:2016-08-08 12:28:59

标签: javascript angularjs google-maps

我正在研究这个谷歌地图项目,但我无法让json工作

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 = {};

};

如果我理解正确,我可以通过使用$ scope.markers来获取数据吗?

4 个答案:

答案 0 :(得分:0)

您应该使用then方法并修改回调中的map对象:

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

答案 1 :(得分:0)

$ scope.markers = data;在异步请求之后调用,因此您的标记:$ scope.markers调用undefined $ scope.markers

答案 2 :(得分:0)

您没有在$ scope.map.markers中获取数据,因为来自http的数据值是异步的,并且$ scope.markers未初始化

TRY:

 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 = {};
   });


};

答案 3 :(得分:0)

不幸的是没有。分配$scope.markers = data;时,您正在更改变量引用的对象,但$scope.map.makers仍在引用旧值(undefined)。

最简单的两种方法:

1)直接引用变量:

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

2)用手表:

$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; 
});