6

app.js看起來像AngularJS:服務查詢返回結果爲零

var app = angular.module('pennytracker', [ 
    '$strap.directives', 
    'ngCookies', 
    'categoryServices' 
]); 

app.config(function($routeProvider) { 
    console.log('configuring routes'); 
    $routeProvider 
    .when('/summary', { templateUrl: '../static/partials/summary.html'}) 
    .when('/transactions', { templateUrl: '../static/partials/transaction.html', controller: 'AddTransactionController' }) 
}); 

,而我的app/js/services/categories.js看起來像

angular.module('categoryServices', ['ngResource']). 
    factory('Category', function($resource){ 
    return $resource(
     '/categories/:categoryId', 
     {categoryId: '@uuid'} 
    ); 
    }); 

,我有作爲

.when('/transactions', { templateUrl: '../static/partials/transaction.html', controller: 'AddTransactionController' }) 

的路線和我的控制器app/js/controllers/transactionController.js看起來像

function AddTransactionController($scope, $http, $cookieStore, Category) { 
// some work here 
    $scope.category = Category.query(); 
    console.log('all categories - ', $scope.category.length); 
} 

當我運行我的應用程序,我看到的console.log作爲

all categories - 0 

什麼,我做錯了什麼?

回答

15

Category.query()是異步的。它立即返回一個空陣列和從該請求後,當響應到達時將結果 - 從http://docs.angularjs.org/api/ngResource.$resource

它認識到調用$資源對象方法 立即返回一個空引用(對象或數組是重要取決於 isArray)。一旦數據從服務器返回,現有的 引用就會填充實際數據。這是一個有用的技巧 ,因爲通常該資源被分配給由視圖呈現的模型,然後 。有一個空對象導致沒有渲染, 一旦數據從服務器到達,然後對象與數據填充 和視圖自動重新呈現自己顯示 新數據。

如果您需要訪問你的控制器的結果你應該這樣做在回調函數是這樣的:

$scope.category = Category.query(function(){ 
    console.log('all categories - ', $scope.category.length); 
}); 
+0

吉茲:(,我怎麼會錯過在文檔中的部分非常感謝你@joakimbi,它現在有效 – daydreamer 2013-05-06 03:27:32