2013-08-29 137 views
0

分毫不差我有如下我的应用程序设置:角资源计时问题

var myApp = angular.module('app', []); 

myApp.factory('MotorList', ['$resource', function($resource) { 
    return $resource(baseURL + 'MotorList.json', {}, {}); 
}]); 

myApp.factory('MotorDataManager', function(MotorList) { 
var List; 

MotorList.query().$then(function(value){ 
    List = value.data; 
}) 

return { 
    getFullList: function() { 
    return List; 
    } 
    anotherFunction: function { ... } 
} 

}); 

myApp.controller('MainCtrl', function($scope,MotorDataManager){ 
    $scope.tableData = MotorDataManager.getFullList(); 
}) 

在我的前端我有一个NG-重复,通过$ scope.tableData循环。 但是我面临的问题是$ scope.tableData永远不会呈现。资源工作正常。它确实返回数据,但我觉得这是一个计时问题,但我不知道如何解决它。

+0

嘿,我对angular的.query()函数的理解将返回索引。是否有一个特别的原因,你必须编写自己的方法? –

+0

Angular的查询返回资源对象 – runtimeZero

+0

也可以提供你的html模板吗? –

回答

0

当然,这是一个计时问题。当你打电话给MotorDataManager.getFullList()时,你得到undefined,因为设置它的回调永远不会被设置。所以,$scope.tableData是未定义的。

您需要$scope.tableData以引用更改的内容。下面是做这件事:

myApp.factory('MotorDataManager', function(MotorList) { 
    var list = []; 

    MotorList.query().$then(function(value){ 
    angular.forEach(value, function(item) { 
     list.push(item); 
    }); 
    }); 

    return { 
    getFullList: function() { 
     return list; 
    } 
    } 
}); 

myApp.controller('MainCtrl', function($scope,MotorDataManager){ 
    $scope.tableData = MotorDataManager.getFullList(); 
}); 

在这个例子中,你现在返回一个数组,所以用,$scope.tableData开始将是一个空数组。但是那样可以,因为你现在有一些参考。当$resource返回时,它将填充数组(这是相同的引用),因此您的控制器现在将有一个填充数组。 Angular的数据绑定和消化逻辑应该照顾其余部分。

+0

这不起作用..它会返回以下错误:TypeError:Array.prototype.push调用null或undefined – runtimeZero

+0

对不起......请查看我对“angular.forEach”调用的编辑。无论如何,该函数只是应该将值复制到'list'数组中,而不是覆盖它。 –

+0

时间问题不解决这个 – runtimeZero