在定义的对象中引用时,数组未定义

时间:2015-04-30 12:57:22

标签: javascript angularjs meanjs

这可能是一个简单的解决方案,但它让我疯狂。我有一行代码,我试图在属性中引用我的数组。我是AngularJS的新手,所以这可能是一个非常愚蠢的问题。

这样调用数组:

console.log($scope.pickupleague.players);

返回: undefined

认为我的对象$ scope.pickupleague不起作用,我打电话:

console.log($scope.pickupleague);

但是,这会返回我要找的所有内容。对象中有7个单独的项目。现在我没有为我的功能做任何额外的事情。整件事就是这样:

$scope.setSubscribedPlayers = function(leagueDetails) {
        console.log($scope.pickupleague.players);
    };

一旦设置了$ scope.pickupleague,我就调用此函数。据我所知,再一次没有发生任何疯狂事件。该功能如下所示:

$scope.findOne = function() {
        $scope.pickupleague = Pickupleagues.get({ 
            pickupleagueId: $stateParams.pickupleagueId
        });

        $scope.listPlayers = $scope.setSubscribedPlayers($scope.pickupleague);
    };

对此的任何帮助都会很棒。我很难过,我觉得这样的事情应该是一个非常简单的解决方案。

非常感谢。

编辑 - 添加了$ scope.pickupleague的内容

__v: 17
_id: "55323371b2873f32099aa435"
address: "1234 Dufferin Street"
city: "Thornhill"
contactname: "Mike L"
cost: "30"
country: "Canada"
created: "2015-04-18T10:35:29.939Z"
description: "This is just a game for some beginners to get together and play."
email: "email@gmail.com"
name: "Friday Night Hockey"
phone: "416-123-4433"
players: Array[7]
0: Object
    _id: "5540b318ffe8b25b749da4fd"
    playerID: "553fda45d014e77bc659d16f"
1: Object
    _id: "5540b3c5ffe8b25b749da4fe"
    playerID: ""
2: Object
    _id: "5540b3eeffe8b25b749da4ff"
    playerID: ""
__proto__: Object
3: Object
    _id: "5540b434ffe8b25b749da500"
    playerID: ""
__proto__: Object
4: Object
    _id: "5540b4efffe8b25b749da501"
    playerID: "553fda45d014e77bc659d16f"
__proto__: Object
5: Object
    _id: "5540b567ffe8b25b749da502"
    playerID: "553fda45d014e77bc659d16f"
__proto__: Object
6: Object
    _id: "5540b5adffe8b25b749da503"
    playerID: "552af744291bddc5b98934c0"
length: 7
__proto__: Array[0]
postalcode: "1a2 b3c"
province: "Ontario"
skillLevel: "Rookie"
time: "11:00pm - 12:00 am"

2 个答案:

答案 0 :(得分:0)

Pickupleagues.get({});似乎是一个异步函数。因此,$scope.pickupleague是您致电时的承诺。将您的其他函数放在异步函数的回调中:

$scope.findOne = function() {
    $scope.pickupleague = Pickupleagues.get({ 
        pickupleagueId: $stateParams.pickupleagueId
    }).then(function(){
        // Success callback
        $scope.listPlayers = $scope.setSubscribedPlayers($scope.pickupleague);
    });
};

答案 1 :(得分:0)

感谢devqon的帮助,我能够走上正轨。我切换了从Pickupleagues.get()加载数据,而是改为使用$ http.get()。这让我在完成正在加载的数据时获得成功声明。然后,我可以调出所需的功能。

$http.get('/pickupleagues/'+ $stateParams.pickupleagueId).
    success(function(data, status, headers, config) {
        $scope.pickupleague = data;
        $scope.listPlayers = $scope.setSubscribedPlayers();
    }).
    error(function(data, status, headers, config) {
        console.log(data);
    });

希望这有助于解决方案帮助其他人。事实证明,使用默认的Mean.js调用可能不是这种情况的最佳解决方案。