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) {} }; });
Promises in AngularJS are provided by the built-in $q service. They provide a way to execute asynchronous functions in series by registering them with a promise object. {info} Promises have made their way into native JavaScript as part of the ES6 specification.
A factory which creates a resource object that lets you interact with RESTful server-side data sources. The returned resource object has action methods which provide high-level behaviors without the need to interact with the low level $http service.
ngResource is the module of the AngularJS resource service that can be used to fetch data from back end RESTFul API. The second code snippet is a great example, the newly created module has just one dependency, which is ngResource . The next step is to inject the object called $resource into the controller/factory/etc.
What is Factory in AngularJS? Factory is an angular function which is used to return the values. A value on demand is created by the factory, whenever a service or controller needs it. Once the value is created, it is reused for all services and controllers. We can use the factory to create a service.
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; });
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With