【问题标题】:Angular: Access resource value in controllerAngular:访问控制器中的资源值
【发布时间】:2013-04-24 15:31:39
【问题描述】:

我的 JavaScript 很糟糕,而且对 Angular 很陌生,所以请多多包涵。

我的服务器正在返回这个:

{"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

在控制台中,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 是一个resource 实例,但我如何才能直接获取这些值?

如果我在控制器中设置了$scope.eventDetail,我将能够通过模板中的{{ eventDetail.latitude }} 访问它。

我到底如何在控制器中做到这一点?

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

    来自the docs

    重要的是要意识到调用 $resource 对象方法会立即返回一个空引用(对象或数组取决于 isArray)。从服务器返回数据后,现有引用将填充实际数据。

    因此,除非您将其放入回调函数中,否则您的日志记录将无法正常工作,如下所示:

    function mapCtrl($scope, Event) {
      Event.get({eventId: $scope.eventId},function(eventDetail){
        //on success callback function
        console.log(eventDetail);
        console.log(eventDetail.latitude);
      });
    }
    

    如果您出于某种原因不想使用resource,您可以使用$http service

    $http.get(url).then(function(response){console.log(response.data);});
    

    【讨论】:

    • 我认为令我困惑的是我可以看到返回的数据,只是认为我的 javascript-fu 真的很糟糕,我不知道如何遍历资源对象。谢谢你。
    • 啊哈!清如泥。这次真是万分感谢。挖掘 2012 年使用 $resource 的代码库
    猜你喜欢
    • 1970-01-01
    • 2012-02-10
    • 2019-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-28
    • 1970-01-01
    相关资源
    最近更新 更多