2013-08-29 64 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