Angular: Access resource value in controller
angularjs, javascript
Solution
From the docs:
It is important to realize that invoking a $resource object method immediately returns an empty reference (object or array depending on isArray). Once the data is returned from the server the existing reference is populated with the actual data.
So your logging wont work unless you put it in a callback function, like this:
function mapCtrl($scope, Event) {
Event.get({eventId: $scope.eventId},function(eventDetail){
//on success callback function
console.log(eventDetail);
console.log(eventDetail.latitude);
});
}
If you for some reason don't want to work with a `resource` you can use the `$http` service:
$http.get(url).then(function(response){console.log(response.data);});
Problem
I'm terrible at javascript and very new to Angular so do bear with me. My server is returning this: ``` {"latitude": 3.172398, "name": "Event", "longitude": 101.6739005} ``` services.js ``` var mapModule = angular.module('map.services', ['ngResource']); mapModule.factory('Event', function($resource) { return $resource('/custom_api/get_event_details/:eventId/', {eventId: '@id'}); }); ``` controller.js ``` function mapCtrl($scope, Event) { var eventDetail = Event.get({eventId: $scope.eventId}); console.log(eventDetail); console.log(eventDetail.latitude); } ``` I'm trying to access the json returned by my server via `eventDetail.latitude` but I am getting `undefined`. In console, `console.log(eventDetail)` looks like: ``` e {$get: function, $save: function, $query: function, $remove: function, $delete: function} latitude: 3.172398 longitude: 101.6739005 name: "abc" __proto__: e ``` I get that `eventDetail` is a `resource` instance but how do I just get to the values directly? If I had set `$scope.eventDetail` in my controller, I would be able to access it via `{{ eventDetail.latitude }}` in my template. How on earth do I do this in the controller?