Angular:访问控制器中的资源值 [英] Angular: Access resource value in controller
问题描述
我在 JavaScript 方面很糟糕,而且对 Angular 非常陌生,所以请耐心等待.
I'm terrible at javascript and very new to Angular so do bear with me.
我的服务器正在返回:
{"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);
}
我正在尝试通过 eventDetail.latitude
访问我的服务器返回的 json,但我得到 undefined
.
I'm trying to access the json returned by my server via eventDetail.latitude
but I am getting undefined
.
在控制台中,console.log(eventDetail)
看起来像:
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
我知道 eventDetail
是一个 resource
实例,但如何直接获取值?
I get that eventDetail
is a resource
instance but how do I just get to the values directly?
如果我在控制器中设置了 $scope.eventDetail
,我将能够通过模板中的 {{ eventDetail.latitude }}
访问它.
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?
推荐答案
来自 文档一个>:
重要的是要意识到调用 $resource 对象方法会立即返回一个空引用(取决于 isArray 的对象或数组).从服务器返回数据后,现有引用将填充实际数据.
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);
});
}
如果您出于某种原因不想使用 resource
,您可以使用 $http
服务:
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);});
这篇关于Angular:访问控制器中的资源值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!