AngularJS 资源承诺

我有一个使用 $resource 的简单控制器:

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


$scope.regions = Regions.query();

我在一个指令中使用这个控制器(在 link 函数中)

var regions = scope.regions;

但是区域是未定义的,这个调用是异步的,这很符合逻辑。

我的问题是,如何等待结果和区域是一个数组的所有数据?

UPDATE :

这里是指令的定义

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) {}
};
});
101835 次浏览

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 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;
});

You could also do:

Regions.query({}, function(response) {
$scope.regions = response;
// Do stuff that depends on $scope.regions here
});
/*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;
});