2015-04-21 43 views
1

如何從$ resoure調用中檢索值並在JS中使用它,不僅僅在我的視圖中使用數據綁定?

我有這樣的JSON:

{ 
    "id": 18, 
    "name": "adsfadsf", 
    "type_of_dish": "Tacos", 
    "cost": "5.95", 
    "notes": "bla bla bla", 
    "totalrecipes": 1, 
    "dish_recipes_attributes": [ 
     { 
      "recipe_id": 28, 
      "no_recipe": 1, 
      "name": "tacos al pastor piña", 
      "cost_portion": "5.95" 
     } 
    ] 
} 
在我的JS

$scope.dish = Dish.get({id: $routeParams.id}); 

我需要得到的價值 「totalrecipes」,我這個嘗試沒有全成:

var totalrecipes = $scope.dish.totalrecipes; 
console.log(totalrecipes); //Undefined 
console.log($scope.dish); // [object Object] 

但在我看來一切正常:

{{dish.totalrecipes}} // 1, It's OK! 

回答

5

記住一個資源的作用功能異步和只返回承諾對象。您可以閱讀$resource$q文檔中的內容。該視圖實際上是設計爲在履行承諾時實現自我更新,這就是爲什麼該值會顯示在您的視圖中。

考慮下面的例子:

$scope.dish = Dish.get({id: 123}) 
alert($scope.dish.totalrecipes); 

在這種情況下,直到實際值加載$scope.dish將被分配一個承諾對象(其可以稍後在任何時間點發生,或根本不)。

相反,你可以使用一個回調方法,可以直接作爲get函數的參數,或者使用承諾 API:

$scope.dish = Dish.get({id: 123}, function(dish) { 
    alert(dish.totalrecipes); 
}); 

或者:

$scope.dish = Dish.get({id: 123}) 
$scope.dish.$promise.then(function(dish) { 
    alert(dish.totalrecipes); 
}); 
+0

偉大的!我已經明白它是如何工作的!謝謝! –

+0

樂意幫忙! :) – helmbert

+0

@IsraelBarba,也請考慮接受這個答案,如果它完全回答你的問題。 ;) – helmbert