sup*_*er9 7 javascript angularjs
我对javascript非常糟糕,对Angular很新,所以请耐心等待.
我的服务器正在返回:
{"latitude": 3.172398, "name": "Event", "longitude": 101.6739005}
Run Code Online (Sandbox Code Playgroud)
services.js
var mapModule = angular.module('map.services', ['ngResource']);
mapModule.factory('Event', function($resource) {
return $resource('/custom_api/get_event_details/:eventId/',
{eventId: '@id'});
});
Run Code Online (Sandbox Code Playgroud)
controller.js
function mapCtrl($scope, Event) {
var eventDetail = Event.get({eventId: $scope.eventId});
console.log(eventDetail);
console.log(eventDetail.latitude);
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试访问我的服务器返回的json,eventDetail.latitude但我得到了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
Run Code Online (Sandbox Code Playgroud)
我得到的eventDetail是一个resource实例,但我如何直接获取值?
如果我已经$scope.eventDetail在我的控制器中设置,我将能够通过{{ eventDetail.latitude }}我的模板访问它.
我怎么在控制器中做到这一点?
来自文档:
重要的是要意识到调用$ resource对象方法会立即返回一个空引用(取决于isArray的对象或数组).从服务器返回数据后,将使用实际数据填充现有引用.
所以你的日志记录不会工作,除非你把它放在一个回调函数中,如下所示:
function mapCtrl($scope, Event) {
Event.get({eventId: $scope.eventId},function(eventDetail){
//on success callback function
console.log(eventDetail);
console.log(eventDetail.latitude);
});
}
Run Code Online (Sandbox Code Playgroud)
如果您出于某种原因不想使用a,resource您可以使用该$http服务:
$http.get(url).then(function(response){console.log(response.data);});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6798 次 |
| 最近记录: |