角:在控制器访问资源价值 [英] Angular: Access resource value in controller
问题描述
我在JavaScript的可怕和非常新的角所以请多多包涵。
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);
}
我想通过 eventDetail.latitude
来访问我的服务器返回的JSON,但我得到未定义
。
I'm trying to access the json returned by my server via eventDetail.latitude
but I am getting undefined
.
在控制台中,的console.log(eventDetail)
如下:
e {$get: function, $save: function, $query: function, $remove: function, $delete: function}
latitude: 3.172398
longitude: 101.6739005
name: "abc"
__proto__: e
我得到的 eventDetail
是资源
实例,但我怎么刚刚得到的值直接?
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?
推荐答案
要认识到,调用$资源对象方法立即返回一个空引用(对象或数组取决于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);
});
}
如果您由于某种原因不想用资源工作
您可以使用的 $ 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);});
这篇关于角:在控制器访问资源价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!