Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
149 views
in Technique[技术] by (71.8m points)

javascript - Angular: Access resource value in controller

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...