AngularJS resource promise

AngularjsPromiseAngular Resource

Angularjs Problem Overview


I've got a simple controller that use $resource :

 var Regions = $resource('mocks/regions.json');

 $scope.regions = Regions.query();

I'm using this controller in a directive (in the link function)

var regions = scope.regions;

But regions is undefined. It's pretty logic the call is asynchronous.

My question is how can i do to wait the result and regions be an array with all data ?

UPDATE : 

Here the definition of the directive

app.directive('ngMap', function() {
  return {
    restrict: 'EA',
    replace: 'true',
    scope: {

    },
    template: '<div id="map"></div>',
    controller: 'AccordMapCtrl',
    link: function(scope, element, attrs) {
      var regions = scope.regions;
      console.log(regions);

      for (var region in regions) {}
    };
  });

Angularjs Solutions


Solution 1 - Angularjs

If you want to use asynchronous method you need to use callback function by $promise, here is example:

var Regions = $resource('mocks/regions.json');

$scope.regions = Regions.query();
$scope.regions.$promise.then(function (result) {
    $scope.regions = result;
});

Solution 2 - Angularjs

If you're looking to get promise in resource call, you should use

> Regions.query().$q.then(function(){ .... })

Update : the promise syntax is changed in current versions which reads

Regions.query().$promise.then(function(){ ..... })

Those who have downvoted don't know what it was and who first added this promise to resource object. I used this feature in late 2012 - yes 2012.

Solution 3 - Angularjs

You could also do:

Regions.query({}, function(response) {
    $scope.regions = response;
    // Do stuff that depends on $scope.regions here
});

Solution 4 - Angularjs

/*link*/
$q.when(scope.regions).then(function(result) {
	console.log(result);
});

var Regions = $resource('mocks/regions.json');
$scope.regions = Regions.query().$promise.then(function(response) {
	return response;
});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionThomas PonsView Question on Stackoverflow
Solution 1 - AngularjsAndrey PushkarevView Answer on Stackoverflow
Solution 2 - AngularjsMahbubView Answer on Stackoverflow
Solution 3 - AngularjsAndreasView Answer on Stackoverflow
Solution 4 - AngularjsDW.DingView Answer on Stackoverflow