2014-01-16 45 views
0

我想打电话给我拥有的宁静服务,并在控制器中填充数据,以便我可以在JVector地图上填充数据。我很有可能采取了错误的做法(应该可能使用指令)。我知道该服务工作正常,我正在获取我期望的数据。但是,当我通过console.log检查json中的数据时,我得到的是未定义的。我相信这是因为我只是得到了一个承诺,数据没有实际填充,直到我将它显示在页面上。我很可能做错了什么。AngularJS资源 - 在控制器内部填充示波器数据

任何建议将不胜感激。

模块:

var app = angular.module('app', ['ngResource']). 
     factory('mapDataSvc', function ($resource) { 
      return $resource('api/sites', {}); 
     }); 

控制器:

var mapCtrl = function ($scope, mapDataSvc) { 
    //http://coder1.com/articles/consuming-rest-services-angularjs 
    $scope.mapData = {}; 

    mapDataSvc.query(function (response) { 
     // Assign the response INSIDE the callback 
     $scope.mapData = response; 
    }); 

//I see the sites array in this log output 
console.log($scope.mapData); 

//This is showing undefined. 
    console.log($scope.mapData.Sites); 

} 

例JSON:

{ 
    Sites: [{ 
     VendorName: "MyVendor", 
     SystemHardwareId: 111111, 
     Longitude: 45.22, 
     Longitude: -71.0418 
    }] 
} 
+0

你说“我看到网站数组中此日志输出”的评论。但是你不应该在那里看到一个数组,你应该看到一个拥有一个数组的Sites属性。你能澄清这一点吗? – idursun

+0

你是正确的idursun ....它是一个Sites属性,它拥有一个数据数组 – scarpacci

回答

0

似乎之前是属于MapData内部mapDataSvc.query初始化您的console.log被执行。尝试将它移动到mapDataSvc.query这样的:

var mapCtrl = function ($scope, mapDataSvc) { 
//http://coder1.com/articles/consuming-rest-services-angularjs 
$scope.mapData = {}; 

mapDataSvc.query(function (response) { 
    // Assign the response INSIDE the callback 
    $scope.mapData = response; 

    //I see the sites array in this log output 
    console.log($scope.mapData); 

    //Should be not undefined. 
    console.log($scope.mapData.Sites); 
}); 

}