Angularjs变量在函数外部未定义

时间:2014-08-27 10:01:47

标签: angularjs resources undefined

每当我调用cardslength变量或者只调用cards.length时,我都会在函数外部进行未定义。这是否意味着我需要使用$ scope?我正在使用角度1.0.5顺便说一句,因为这是我正在遵循的教程的一部分,我需要使用该版本。

这是我的代码:

eventsApp.factory('eventData', function ($resource, $q) {
var resource = $resource('/data/event/:id', {id: '@id'});


//////////////////////This is the part that doesn't seem to be working//////////
var cardslength
var cards = resource.query(function() {
        cardslength = cards.length;
        });
        console.log(cardslength);
        console.log(cards.length);
////////////////////////////////////////////////////////////////////////////////


return {
    getEvent: function () {
        var deferred = $q.defer();
        resource.get({id: 1},
            function (event) {
                deferred.resolve(event);
            },
            function (response) {
                deferred.reject(response);
            });

        return deferred.promise;
    },
    save: function(event) {
        var deferred = $q.defer();
        event.id = 1234;
        resource.save(event,
            function(response) { deferred.resolve(response);},
            function(response) { deferred.reject(response);}
        );
        return deferred.promise;
    }
};
});

1 个答案:

答案 0 :(得分:1)

console.log.query()完成之前执行。为避免这种情况,请尝试以下操作:

var cards = resource.query(function() {
    cardslength = cards.length;
}).then(function(){
    console.log(cardslength);
    console.log(cards.length);
});