1

How I can retrieve a value from a call with $resoure and use it in JS, no only in my views with data binding?

I have this 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"
        }
    ]
}

in my JS:

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

I need to get the value "totalrecipes", I've tried with this without successfull:

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

But in my view everything is ok:

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

1 Answer 1

5

Remember that the action functions of a resource are asynchronous and return only a promise object. You can read up on that in the $resource and $q documentations. The view is actually designed to update itself once a promise is "fulfilled", that's why the value is displayed in your view.

Consider the following example:

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

In this case, $scope.dish will be assigned a promise object until the actual value is loaded (which may happen at any point later in time, or not at all).

Instead, you can use a callback method, either directly as argument of the getfunction, or using the promise API:

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

Alternatively:

$scope.dish = Dish.get({id: 123})
$scope.dish.$promise.then(function(dish) {
    alert(dish.totalrecipes);
});
Sign up to request clarification or add additional context in comments.

1 Comment

@IsraelBarba, please also consider accepting this answer if it fully answered your question. ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.