0

I'm working with AngularJS a lot right now, but I believe that this is more of a JavaScript question than anything else. Here's snippet from an example controller. Let's assume that it contains an Angular service (defined by me) called 'Restaurants' that I can make queries against.

$scope.myFunction = function() {

    Restaurants.query(function(restaurants) {
        // How to return 'restaurants'?
        return restaurants;
    }
}

The result of Restaurants.query() is handled by the function argument I gave it. My ultimate goal here is to have the 'restaurants' variable be the return value of 'myFunction()'. But when I return from within the nested callback, it doesn't work.

Two questions: - Within the callback, where does the return value ('restaurants') go? - How should I restructure this code so that 'restaurants' can be the return value of 'myFunction()'?

Joey Mason
  • 707
  • 1
  • 8
  • 15
  • If `Restaurants.query()` is asynchronous, then you won't be able to `return restaurants`. `$scope.myFunction()` will always exit before `restaurants` has actually become available. "[How to return the response from an AJAX call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call)" – Jonathan Lonowski Apr 26 '14 at 22:09
  • What is your ultimate goal here? Do you want to bind against `myFunction` to have access to `restaurants` from inside a template? In this case, you could just define `$scope.restaurants` and then you do `$scope.restaurants = restaurants` inside your function. – basilikum Apr 26 '14 at 22:55
  • Is `Restaurants` a `$resource` instance ? – gkalpak Apr 27 '14 at 00:07
  • Yes Restaurants is a $resource instance – Joey Mason Apr 27 '14 at 02:06
  • I find myself often initializing variables, (for example, available restaurants), using something like data-ng-init="initRestaurants()". Let's say I want to iterate through a list of restaurants, it would be great to do this: data-ng-repeat="restaurant in getRestaurants()" Where getRestaurants() is a function that returns restaurants – Joey Mason Apr 27 '14 at 02:07

1 Answers1

0

Instead of returning, set a variable on the scope. Something like this:

Restaurants.query(function(restaurants) {
    // How to return 'restaurants'?
    $scope.restaurants = restaurants;
}
jsparks
  • 1,020
  • 1
  • 14
  • 19